[Django]-Average for ratings in Django

5👍

✅

You’re getting the average rating on each review, which will of course just give you the rating for that review as each review only has a single rating. The average of a single number is just that number.

I think what you want is the average for all the ratings for a film. So you’d want a query that looks something like:

Flim.objects.annotate(avg_rating=Avg('review_set__rating')).order_by('-avg_rating')

Also, you can change the name of review_set (which is default for a Foreign Key lookup if no related name is set) to whatever you want by setting related_name='reviews' or whatever you want it to be called on the FK definition.

So:

reviewed_film = models.ForeignKey(Film, related_name='reviews', on_delete=models.CASCADE)

ETA: if you make that change, your query would become:

Flim.objects.annotate(avg_rating=Avg('reviews__rating')).order_by('-avg_rating')

Leave a comment