Julia Ebert
Julia Ebert

Reputation: 1623

Django Nested ManyToMany QuerySet

I have a set of nested manytomany relationships in my Django models where I would like to be able to get all relevant rows 2 connections away. It's set up like this:

class Book(models.Model):
    pass

class Group(models.Model):
    books = models.ManyToManyField(Book)

class Person(models.Model):
    groups = models.ManyToManyField(Group)

Essentially, a person can belong to multiple groups and each group has multiple books, but the same book can be in multiple groups and multiple people are in each group.

I am trying to write a method for Person to list of all of the books for that person. I'm pretty sure it could be done with nested loops, but that's hardly an elegant solution. I'm trying to use QuerySets but getting stuck at the second level. I'm thinking of something along the lines of:

def all_books(self):
    return Book.objects.filter(group__in = self.groups)

But I always get back an empty list. I'm guessing that the problem is with __in, but I don't know what exactly.

Upvotes: 0

Views: 3041

Answers (1)

Peter DeGlopper
Peter DeGlopper

Reputation: 37319

One way is:

def all_books(self):
    return Book.objects.filter(group__person=self)

That'll return all books in at least one group of which the user is a member.

Upvotes: 1

Related Questions