user993563
user993563

Reputation: 19371

Getting many to many fields of many to many association in django model

I have two levels of many to many associations in django. A player can belong to one or many teams. And a team can play one or many tournaments. Given a player i want to know in which all tournaments he has played.

Following is the simplified model:

class Tournament(models.Model):
    name = models.CharField(max_length=100, blank=True, null=True)


class Team(models.Model):
    team_name = models.CharField(max_length=100, blank=True, null=True)
    tournaments_played = models.ManyToManyField(Tournament)

class Player(models.Model):
    player_name = models.CharField(max_length=100, blank=True, null=True)
    belongs_to_team = models.ManyToManyField(Team)    

In my views i tried the following:

pl = Player.objects.get(player_name = "Andrew Flintoff")
ts = pl.belongs_to_team() 

this gives me more than one team, now for each of the team i want to know which tournaments they have played.

qs_list = []
for t in ts:
   team_qs = Team.objects.get(team_name = t)
   tourn = team_qs.tournaments_played.all() 
   qs_list.append(tourn)

and then in my context i can pass the queryset list qs_list. Is there a better/simpler way of doing it??

Upvotes: 0

Views: 817

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239250

 p1_tournaments = Tournament.objects.filter(team__player=p1)

There's an implicit lookup created for every reverse foreign key or m2m field. It's either the lowercased model class or the related_name argument, if specified.

So, essentially, that filter says get the tournaments related to teams that are related to the player, p1.

Upvotes: 3

Related Questions