gpt4 book ai didi

python - Django 用聚合平均值注释

转载 作者:太空宇宙 更新时间:2023-11-04 05:44:05 25 4
gpt4 key购买 nike

在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

最佳答案

您可以像这样使用 book__rating 访问出版商的书籍:

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

关于python - Django 用聚合平均值注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32883880/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com