1👍
The fact that the Review
(?) model has a rating and there is an AddedReview
model is quite bizarre, but anyway. You can not order by a property, since the database does not know about properties. Furthermore the property requires extra queries, which is not very efficient.
You can annotate the query and order. You thus should omit the avg_rating
property, and work with:
from django.db.models import Count, F, Sum
Review.objects.annotate(
avg_rating=(F('rating') + Sum('addedreview__rating', default=0))
/ (Count('addedreview__rating') + 1)
).order_by('-avg_rating')[:5]
But likely a simpler modeling where you only store ratings in the AddedReview
model would simplify this (and might make it more efficient):
from django.db.models import Avg
# version if you only add ratings to the AddedReview model
Review.objects.annotate(avg_rating=Avg('addedreview__rating')).order_by(
'-avg_rating'
)[:5]
Source:stackexchange.com