1👍
✅
If you don’t want to denormalize, you can use annotation.
Assume your models are something like:
class Service(models.Model):
name = models.CharField(max_length=5)
class Order(models.Model):
name = models.CharField(max_length=5)
service = models.ForeignKey(Service)
class Rating(models.Model):
order = models.OneToOneField('Order')
grade = models.IntegerField()
Then you can annotate and query by the average:
Service.objects.annotate(avg_rate=Avg('order__rating__grade')).order_by('avg_rate')
👤eran
Source:stackexchange.com