Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django filter objects with at least one many-to-many having attribute of value

I'm looking to do a complex filter using Django's ORM.

Models:

class Book(models.Model):
    title = models.TextField()
    bestseller = models.BooleanField(default=False)

class Author(models.Model):
    name = models.TextField()
    books = models.ManytoManyField(Book)

How would I query for all authors who have at least one best-selling book?

Query:

best_authors = Author.objects.filter(<relevant filter>)

Edit:

According to the documentation, the following should work:

best_authors = Author.objects.filter(books__bestseller=True)

Unfortunately, that ends up returning repeated author objects (the same author for each bestselling book of his/hers, over and over).

like image 742
Bradford Wade Avatar asked Feb 25 '14 21:02

Bradford Wade


Video Answer


1 Answers

best_authors = Author.objects.filter(books__bestseller=True).distinct()

The filter() does a JOIN with the Books table and produces all rows where bestseller==True. The distinct() ensures that each author is listed only once in the results.

like image 85
Kevin Christopher Henry Avatar answered Sep 22 '22 09:09

Kevin Christopher Henry