开发者

Django: query spanning multiple many-to-many relationships

开发者 https://www.devze.com 2022-12-31 08:42 出处:网络
I\'ve got some models set up like this: class AppGroup(models.Model): users = models.ManyToManyField(User)

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(gro开发者_如何学编程ups_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?


Use the double-underscore format to traverse relations.

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号