Brett Gmoser
Brett Gmoser

Reputation: 1746

Django QuerySet to return unique objects in ManyToMany fields

Given the following models:

class Author(models.Model):
  name = models.CharField()

class Book(models.Model):
  title = models.CharField()
  published_year = models.PositiveIntegerField()
  authors = models.ManyToManyField(Author)

Let's say I want to get all of the authors who have authored a book published in the year 2008. I can do the following:

Book.objects.filter(published_year=2008).values_list('authors__name').distinct()

That'll get me a list of authors - almost exactly what I want, except that instead of just the names, I want the Author objects. I can achieve that somewhat by doing this:

authors = []
for b in Book.objects.filter(published_year=2008):
  for a in b.authors.all():
    if a not in authors:
      authors.append(a)

But that seems totally unnecessary. Is it possible to get the QuerySet to do that work for me? Thanks!

Upvotes: 0

Views: 525

Answers (1)

levi
levi

Reputation: 22697

Just use backward relationship

Author.objects.filter(book__published_year=2008).all()

From Django docs

Reverse m2m queries are supported (i.e., starting at the table that doesn’t have a ManyToManyField):

Upvotes: 1

Related Questions