Search code examples
djangodjango-modelsdjango-orm

Build a query to get grouped average of multiples many to one instances


I'm having two models :

class Club(models.Model):
   club_tag = models.CharField(primary_key=True)

class Player(models.Model):
   rating = models.FloatField(default=0)
   club = models.ForeignKey(Club, ...) 

My objective is to get the top 10 of clubs with the best average rating players, in decreasing order.

In this situation the Club has an average rating (Which is its player's average) and is ranked thanks to it.

I'm having a hard time figuring out how to pull this request, can someone give me directions please ? Thanks


Solution

  • I think I've figured it out, so here is the solution :

    Club.objects.annotate(avg_bcr=Avg("player__rating")).order_by("-avg_bcr")[:10]