I'm modelling amateur soccer Games where two teams of players play against each other. I'm trying to annotate the QuerySet with the number of players in each team to then identify games with different number of players in each team.
The models I have are pretty straight forward:
class Player(models.Model):
nickname = models.CharField(...)
class Team(models.Model):
players = models.ManyToManyField(Player)
class Game(modeos.Model):
team1 = models.ForeignKey(Team)
team2 = models.ForeignKey(Team)
When I go to the shell (python manage shell) and execute the following command to get the number of players of the teams in each match I got the expected results:
[(game.team1.players.count(), game.team2.players.count()) for game in Game.objects.all()]
[(7, 7), (7, 10), (7, 7), (7, 7), (7, 7)]
However, when I try to do the same with annotations:
Game.objects.annotate(t1c=Count('team1__players'), t2c=Count('team2__players')).values('t1c','t2c')
I got incorrect results:
<QuerySet [{'t1c': 49, 't2c': 49}, {'t1c': 70, 't2c': 70}, {'t1c': 49, 't2c': 49}, {'t1c': 49, 't2c': 49}, {'t1c': 49, 't2c': 49}]>
Which are the multiplication of both values.
What am I doing wrong?