user764357
user764357

Reputation:

Find items that aren't in a many to many relationship in Django

I have some models, where Books can have many Authors and vice versa:

class Book(models.Model):
    name  = models.CharField(max_length=140)

class Author(models.Model):
    name  = models.CharField(max_length=140)
    books = models.ManyToManyField(Book, related_name="authors")

I need to find all Books that have no author from a Book queryset, yet I can't find an appropriate .filter() or .exclude() clause that will do it.

Can I do this from a queryset?

Upvotes: 0

Views: 32

Answers (1)

Selcuk
Selcuk

Reputation: 59184

You can simply write

Book.objects.filter(author_set=None) 

or, if you have an existing query

book_queryset.filter(author_set=None) 

Upvotes: 2

Related Questions