Reputation: 19371
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()
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
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