[Fixed]-Django aggregation/annotation

1πŸ‘

βœ…

Here is what you can do:

  1. You have a M2M relation between Team and Player, create it.

    class Player(models.Model):
        name = models.CharField(...)
    
        teams = models.ManyToManyField(Team, through='TeamHasPlayer')
    
  2. Get your Team queryset and using the reverse relation prefetch the team.players

    teams = Team.objects.all().prefetch_related('player_set')
    
  3. Now create your team dict:

    team_dict = {}
    for team in teams:
        team_dict[team.name] = list(team.player_set.all())
    
πŸ‘€Todor

0πŸ‘

I would do this in this way, which is more readable and maintainable.

dic_ = {}
for team in Team.objects.all():
    dic_[team.name] = team.teamhasplayer_set.values_list('player', flat=True)
πŸ‘€doniyor

Leave a comment