Django: multiple-to-many relationship query

I have several models configured like this:

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

Custom objects come from django authentication system.

Now I'm trying to get all the notifications related to the groups of which the current user is a part. I tried..

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

But this gives an error:

more than one row returned subquery used as expression

I assume group_to_notify checks for multiple groups.

How can I get all notifications intended for the user, based on the groups in which he is a part?

+4
source share
1 answer

Use the double underscore format to move relationships.

 Notification.objects.filter(groups_to_notify__users=request.user) 
+6
source

Source: https://habr.com/ru/post/1310527/


All Articles