Django:跨越多个多对多关系的查询 [英] Django: query spanning multiple many-to-many relationships

查看:49
本文介绍了Django:跨越多个多对多关系的查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经建立了一些这样的模型:

I've got some models set up like this:

class AppGroup(models.Model):
  users = models.ManyToManyField(User)

class Notification(models.Model):
  groups_to_notify = models.ManyToManyField(AppGroup)

User对象来自django的身份验证系统.

The User objects come from django's authentication system.

现在,我正在尝试获取与当前用户所属的组有关的所有通知.我已经尝试过了.

Now, I am trying to get all the notifications pertaining to the groups that the current user is a part of. I have tried..

notifications = Notification.objects.filter(groups_to_notify=AppGroup.objects.filter(users=request.user))

但这会导致错误:

由a返回的多行子查询用作表达式

more than one row returned by a subquery used as an expression

我想这是因为groups_to_notify正在检查多个组.

Which I suppose is because the groups_to_notify is checking against several groups.

如何根据用户所属的组来获取针对用户的所有通知?

How can I grab all the notifications meant for the user based on the groups he is a part of?

推荐答案

使用双下划线格式遍历关系.

Use the double-underscore format to traverse relations.

Notification.objects.filter(groups_to_notify__users=request.user)

这篇关于Django:跨越多个多对多关系的查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆