Django: query spanning multiple many-to-many relationships

最后都变了- 提交于 2021-02-18 22:36:50

问题


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)

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))

But that gives an error:

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

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?


回答1:


Use the double-underscore format to traverse relations.

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


来源:https://stackoverflow.com/questions/2883461/django-query-spanning-multiple-many-to-many-relationships

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!