如何在 django 中执行查询来选择我作为团队成员的所有项目?
我的 django 应用程序中有团队的概念。
class Team(models.Model):
name = models.CharField(max_length=200)
#snip
team_members = models.ManyToManyField(User)
我想获取当前登录用户所属的所有团队。 与
Team.objects.all().filter(request.user.id__in = team_members.all())
此明显类似的东西是行不通的。 有人对如何在不直接使用 sql 的情况下执行此类查询有一些建议吗? 我确实查看了“in”查询的django文档,但我在那里找不到我的用例。
非常感谢! 缺口。
I have the concept of a team in my django app.
class Team(models.Model):
name = models.CharField(max_length=200)
#snip
team_members = models.ManyToManyField(User)
I would like to fetch all teams the currently logged in user is member of. Something along the lines of
Team.objects.all().filter(request.user.id__in = team_members.all())
This obvious doesn't work. Does anyone have some suggestions on how to do such query without going directly to sql? I did look at the django documentation of "in" queries, but I couldn't find my use case there.
Many thanks!
Nick.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这里不需要
in
,Django 会在 ManyToMany 查找中自动处理它。另外,您需要了解数据库字段必须始终位于查找的左侧,因为它们实际上是作为函数的参数进行处理的。
你真正想要的很简单:
或者
You don't need
in
here, Django handles that automatically in a ManyToMany lookup.Also, you need to understand that the database fields must always be on the left of the lookup, as they are actually handled as parameters to a function.
What you actually want is very simple:
or