Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: query spanning multiple many-to-many relationships

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?

like image 256
Brant Avatar asked May 21 '10 15:05

Brant


People also ask

How do you query a many-to-many relationship in Django?

When querying many-to-many relationships, avoid using multiple filter() methods, make use of Q() objects instead. You can check the SQL query of a QuerySet with str(queryset. query) . Check the performance of recently executed SQL queries with django.

What does .values do in Django?

values() Returns a QuerySet that returns dictionaries, rather than model instances, when used as an iterable. Each of those dictionaries represents an object, with the keys corresponding to the attribute names of model objects.


1 Answers

Use the double-underscore format to traverse relations.

Notification.objects.filter(groups_to_notify__users=request.user)
like image 80
Daniel Roseman Avatar answered Nov 07 '22 20:11

Daniel Roseman