Django使用聚合平均值进行注释

时间:2015-10-01 09:20:59

标签: python sql django django-queryset

在django文档的以下示例中,如何获取

Publisher.objects.all()

使用字段average_rating进行注释,使用图书评分的平均值和max_rating使用图书的最高评分进行计算?

from django.db import models

class Author(models.Model):
    name = models.CharField(max_length=100)
    age = models.IntegerField()

class Publisher(models.Model):
    name = models.CharField(max_length=300)
    num_awards = models.IntegerField()

class Book(models.Model):
    name = models.CharField(max_length=300)
    pages = models.IntegerField()
    price = models.DecimalField(max_digits=10, decimal_places=2)
    rating = models.FloatField()
    authors = models.ManyToManyField(Author)
    publisher = models.ForeignKey(Publisher)
    pubdate = models.DateField()

class Store(models.Model):
    name = models.CharField(max_length=300)
    books = models.ManyToManyField(Book)
    registered_users = models.PositiveIntegerField()

我应该能够在查询集之后打印出类似的内容:

for p in Publisher.objects.all().annotate(...):
    print p, p.average_rating, p.max_rating

1 个答案:

答案 0 :(得分:1)

您可以使用book__rating访问发布商的图书,如下所示:

Publisher.objects.annotate(average_rating=Avg('book__rating'), max_rating=Max('book__rating'))