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

一曲冷凌霜 提交于 2021-02-07 02:56:54

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!