【问题标题】:django store incremental numeric values in a table?django 在表中存储增量数值?
【发布时间】:2010-06-24 11:03:49
【问题描述】:

我想做一个排名申请,它会计算平台上传的每门课程的排名。

将下载次数和浏览次数等值存储在表格中是一种好方法吗?

class Courserate(models.Model):
     course = models.ForeignKey(Courses)
     downloads = models.IntegerField(editable = False, default = 0)
     views = models.IntegerField(editable = False, default = 0)
     positive_votes = models.IntegerField(editable = False, default = 0)
     negative_votes = models.IntegerField(editable = False, default = 0) 

另外,当我尝试获取下载次数时,例如,对于属于特定教室的课程,我应该怎么做?我的意思是,这样的查询:

courses = Courses.objects.filter(classroom = userclass)
downloads = Courserate.objects.filter(course = courses).downloads 

下载查询不起作用,我如何“获取”每门课程的下载次数?

【问题讨论】:

    标签: django model integer increment


    【解决方案1】:

    我认为像你一样保存数字很好。 要使查询返回单个对象(过滤器始终返回查询集),您必须使用 get 而不是 filter

    downloads = Courserate.objects.get(course = course).downloads 
    

    如果只有一个对象与您的查询匹配,这应该可以工作,如果有更多匹配,它将引发异常!如果您使用filter,则必须遍历返回的查询集才能访问downloads

    courses = Courserate.objects.filter(course = course)
    for course in courses:
        print course.downloads # do something with downloads here
    

    如果您想获得多门课程并过滤您的CourseRate 对象以获取Courses 列表,请使用__in

    courses = Courserate.objects.filter(course__in = courses)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多