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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With