在Django中的多对多关系中筛选

时间:2019-02-05 17:20:16

标签: python django

我有两个对象团队和锦标赛,

class Tournament(Base):

    name = models.CharField(db_index=True, max_length=255)
tournament = Tournament.objects.get(id=kwargs.get('tournament_id'))

class Team(Base):

    name = models.CharField(db_index=True, max_length=255)
    tournaments = models.ManyToManyField(Tournament)

现在我想过滤一个特定比赛中的球队

tournament = Tournament.objects.get(id=kwargs.get('tournament_id'))
   teams = Team.objects.filter(tournament=tournament) // This doesn't work.

我该怎么做。任何帮助表示赞赏

2 个答案:

答案 0 :(得分:0)

desired_tournament = Tournament.objects.get(id=1)
desired_teams = Team.objects.filter(tournaments__in=[desired_tournament])

答案 1 :(得分:0)

您几乎完全正确。

# This doesn't work.
teams = Team.objects.filter(tournament=tournament)

# This does. Not exactly intuitive, I'll concede.
teams = Team.objects.filter(tournaments=tournament)