问题
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).
回答1:
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.
来源:https://stackoverflow.com/questions/22026314/django-filter-objects-with-at-least-one-many-to-many-having-attribute-of-value