2012-02-08 59 views
0

我如何獲得平均評分?Django過濾器AVG - 評分

型號:

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) 

我嘗試..

等級= Review.objects.filter(供應商=供應商).annotate(AVG( '評級'))

模板:

{{rating.rating__avg}}

回答

5

要得到一個QuerySet一個平均值,則需要使用aggregate而不是annotate

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