Say I have these two models:
class Match(models.Model):
...
class Player(models.Model):
match=models.ForeignKey(Match)
points=models.IntegerField()
I want to calculate the average points per match, meaning I need sum the points of all players, then divide it by the count of matches. I am having a hard time figuring out how to do this efficiently in Django.
I’ve tried Googling, and searching StackOverflow, but I am having a hard time figuring out what terms I should be looking for in the first place.
match = Match.objects.annotate(total_points=Sum('player__points'))
match[0].total_points now returns the total points of one match, I need to sum total_points of every match and divide it by the total matches.
Thanks for the help!
Use
aggregateto sum the total number of points,count()to find the number of matches, then divide in python to get the average number of points per match.