英文:
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 "members" 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 "members"
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>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论