具有中间表的多对多字段的Django查询集

时间:2014-12-20 19:41:46

标签: django django-models

这是我的设置

模型

class League(models.Model):
    league_name = models.CharField(max_length=60)

class Team(models.Model):
    league = models.ForeignKey('League')
    team_name = models.CharField(max_length=60)

class Game(models.Model):
    league = models.ForeignKey('League')
    teams = models.ManyToManyField(Team, through="GameTeams")
    game_heading = models.CharField(max_length=40, null=True, blank=True)

class GameTeams(models.Model):
    game = models.ForeignKey(Game)
    team = models.ForeignKey(Team, null=True, blank=True)

如何获得与特定联赛相关联的所有(游戏,团队)对?这就是我试过的:

league = League.objects.get(pk=1) #This obviously works
league.game_set.gameteams_set.all() #This doesn't work

结果集应该是这样的东西:

league_id | game_id | team_id
1         | 1       | 1
1         | 1       | 2
1         | 1       | 3
1         | 2       | 2
1         | 2       | NULL

1 个答案:

答案 0 :(得分:0)

你可以这样做:

league = League.objects.get(pk=1)
gameteams = GameTeams.objects.filter(game__league=league, team__league=league)