Django过滤AVG - 评级

时间:2012-02-08 12:31:22

标签: django django-models

如何获得平均评分?

型号:

class Review(models.Model):
    vendor = models.ForeignKey(Vendor)
    product = models.ForeignKey(Product ,blank=True, null=True)
    headline = models.CharField(max_length=100)
    review = models.TextField(blank=True, null=True)
    rating = models.IntegerField()
    active = models.BooleanField(default=1)
    created = models.DateTimeField(auto_now_add=True)
    changed = models.DateTimeField(auto_now=True)

我试试..

rating = Review.objects.filter(vendor = vendor).annotate(Avg('rating'))

模板:

{{rating.rating__avg}}

1 个答案:

答案 0 :(得分:5)

要获得查询集的单一平均值,您需要使用aggregate而不是annotate

rating = Review.objects.filter(vendor=my_vendor).aggregate(Avg('rating'))