Django filter objects with at least one multivalued value attribute

I want to make a sophisticated filter using Django ORM.

Model:

class Book(models.Model): title = models.TextField() bestseller = models.BooleanField(default=False) class Author(models.Model): name = models.TextField() books = models.ManytoManyField(Book) 

How can I request all authors who have at least one best-selling book?

Query:

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

Edit:

In accordance with the documentation , the following should work:

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

Unfortunately, this leads to the return of duplicate copyrighted objects (the same author for each best-selling book of his / her, again and again).

+7
python django django-orm
source share
1 answer
 best_authors = Author.objects.filter(books__bestseller=True).distinct() 

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

+5
source share

All Articles