在django模型中获取多对多关联的多对多字段

发布于 2024-12-11 19:11:19 字数 948 浏览 0 评论 0原文

我在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

浊酒尽余欢 2024-12-18 19:11:19
 p1_tournaments = Tournament.objects.filter(team__player=p1)

为每个反向外键或 m2m 字段创建隐式查找。它可以是小写的模型类,也可以是 lated_name 参数(如果指定)。

因此,本质上,该过滤器表示获取与玩家 p1 相关的球队相关的锦标赛。

 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文