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

4👍

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 Reviews.

Leave a comment