开发者

django store incremental numeric values in a table?

开发者 https://www.devze.com 2023-01-04 19:17 出处:网络
I want to make a rank application, that will calculate the rank of each course uploaded on a platform.

I want to make a rank application, that will calculate the rank of each course uploaded on a platform.

Is it a good approach to have stored in a table values like number of downloads, and number of views, like that?

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) 

also, when I'm trying to take the number of downloads, for example, for a course belonging to a specific classroom, how should I do it? I mean, a query like:

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

the downloads query doesn't work, how can I 'take' the number of开发者_StackOverflow downloads for each course?


I think it's fine to save the numbers as you do. To make the query return a single object (filter always returns a queryset) you have to use get and not filter:

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

This should work if only one object matches your query, if there are more matches it will throw an exception! If you are using filter you have to iterate over the returned queryset to access downloads:

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

If you want to get more than one course and filter your CourseRate objects for a list of Courses use __in:

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

精彩评论

暂无评论...
验证码 换一张
取 消