如何从多对多字段获取查询集

huangapple go评论63阅读模式
英文:

How to get a queryset from many to many field

问题

我有这个模型想要检索所有的"members"作为查询集

class Team(models.Model):
    name = models.CharField(max_length=120)
    owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='owner')
    members = models.ManyToManyField(User, related_name='members') # <---

我尝试了这个但它不起作用

Team.objects.all()['members'] # 和
Team.members.all()

<details>
<summary>英文:</summary>

I have this model and i want to retrieve all the &quot;members&quot; as queryset

class Team(models.Model):
name = models.CharField(max_length=120)
owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='owner')
members = models.ManyToManyField(User, related_name='members') # <---

I tried this but its not working

Team.objects.all()['members'] # and
Team.members.all()


</details>


# 答案1
**得分**: 1

team = Team.objects.filter(belonging=group)
members = team.members.all()


<details>
<summary>英文:</summary>

Nevermind i just found that i need to first filter the model and then access &quot;members&quot;

team = Team.objects.filter(belonging=group)
members = team.members.all()


</details>



# 答案2
**得分**: 1

team_object = Team.objects.first()
members = team_object.members.all()
这将获取与 team_object 相关的所有成员。

<details>
<summary>英文:</summary>

    team_object = Team.objects.first()
    members = team_object.members.all()
This will get you all the members related to the team_object

</details>



huangapple
  • 本文由 发表于 2023年2月10日 04:59:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/75404360.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定