我正在寻找使用 Django 的 ORM 做一个复杂的过滤器。
模型:
class Book(models.Model):
title = models.TextField()
bestseller = models.BooleanField(default=False)
class Author(models.Model):
name = models.TextField()
books = models.ManytoManyField(Book)
我如何查询至少拥有一本畅销书的所有作者?
查询:
best_authors = Author.objects.filter(<relevant filter>)
编辑:
根据documentation ,以下应该有效:
best_authors = Author.objects.filter(books__bestseller=True)
不幸的是,这最终会返回重复的作者对象(他/她的每本畅销书都是同一作者,一遍又一遍)。
最佳答案
best_authors = Author.objects.filter(books__bestseller=True).distinct()
filter()
对Books
表执行JOIN
并生成所有bestseller==True
的行>。 distinct()
确保每个作者在结果中只列出一次。
关于python - Django 过滤对象至少有一个多对多属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22026314/