I have a Product model, with a one-to-many relation with a Rating model. I was previously storing an average_stars field in Product model, which I would update everytime a new Rating was added for that Product model. I would have a function in views.py which would return a QuerySet of all Product instances, ordered by average_star. Is there a way to do this more dynamically using a combination of .aggregate and .order_by, or anything along these lines.
In other words, is there a way to calculate the average for each product from all its respective Rating models, and sort them by that attribute? And which approach is better?
Assuming that your
Ratingmodel has astarsfield, then you should useannotate: