在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
答案 0 :(得分:1)
您可以使用book__rating
访问发布商的图书,如下所示:
Publisher.objects.annotate(average_rating=Avg('book__rating'), max_rating=Max('book__rating'))