在django模型中获取多对多关联的多对多字段
我在 django 中有两个级别的多对多关联。一名球员可以属于一支或多支球队。一支球队可以参加一场或多场比赛。给定一个球员,我想知道他参加过的所有比赛。
以下是简化的模型:
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)
在我看来,我尝试了以下操作:
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)
然后在我的上下文中我可以传递查询集列表qs_list
。有更好/更简单的方法吗?
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??
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为每个反向外键或 m2m 字段创建隐式查找。它可以是小写的模型类,也可以是
lated_name
参数(如果指定)。因此,本质上,该过滤器表示获取与玩家
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
.