简体   繁体   English

如何从Django中的外键值求平均值?

[英]How to make an average from values of a foreign key in Django?

I have a book model and a review model like this in Django:我在 Django 中有一个像这样的书籍模型和评论模型:

class Book(models.Model):

    ratings = models.FloatField()


class Review(models.Model):
    book = models.ForeignKey(
        Book,
        on_delete=models.CASCADE,
        related_name='reviews',
    )
    review = models.CharField(max_length=5000)
    score = models.PositiveSmallIntegerField(null=True, blank=True,
                                             validators=[MinValueValidator(0), MaxValueValidator(10)])

How can I create a method in Book to calculate the ratings (which is the average from all Reviews associated to a specific book)?如何在 Book 中创建一种方法来计算评分(这是与特定书籍相关的所有评论的平均值)?

You can implement a property like:您可以实现如下属性:

from django.db.models import Avg

class Book(models.Model):

    @property
    def ratings(self):
        return self.reviews.aggregate(avg_score=Avg('score'))['avg_score']

Or if you need to do this in bulk , you can annotate your queryset:或者,如果您需要批量执行此操作,您可以注释您的查询集:

from django.db.models import Avg

Book.objects.annotate(
    avg_rating=Avg('reviews__score')
)

Book objects that arise from this queryset, will have an extra attribute avg_rating , that contains the average of the score of the related Review s.从此查询集产生的Book对象将具有一个额外的属性avg_rating ,其中包含相关Review的平均score

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM