Django Filter Queryset by Highest Rating

I have a model that allows for ratings of its objects, and I want to be able to filter by the highest rating, which is a number range that can be either a positive or negative integer:

class Thing(models.Model):
    user = models.ForeignKey(User)
    created_on = models.DateTimeField(auto_now_add=True)
    rating = VotingField(can_change_vote=True)
    ....

The VotingField is from a fork of django-ratings.

How do I filter this queryset to order_by the highest number rating out of all Thing objects? Thanks for your ideas!


I'm unsure whether you want highest average or highest sum so you may need to change the annotate

from django.db.models import Sum, Avg

Thing.objects.annotate(avg_rating=Avg('rating__score')).order_by('-avg_rating')
Thing.objects.annotate(sum_rating=Sum('rating__score')).order_by('-sum_rating')

see https://docs.djangoproject.com/en/dev/ref/models/querysets/#annotate

It looks like you are calling your VotingField rating which looks like its essentially a has many to the Vote model. So we want the Sum or Avg of each Thing 's Vote collection's score field. (I think its the score field we want to annotate https://github.com/Kronuz/django-ratings/blob/master/djangoratings/models.py#L15 but I don't use this plugin so do a little research if this isn't what you need)

链接地址: http://www.djcxy.com/p/38652.html

上一篇: Django过滤器JSONField字典列表

下一篇: Django按最高评分筛选查询集