Django过滤具有至少一个具有value属性的多对多对象

时间:2022-09-02 20:14:18

I'm looking to do a complex filter using Django's ORM.

我想用Django的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 个解决方案

#1


6  

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.

filter()与Books表进行JOIN并生成bestseller == True的所有行。 distinct()确保每个作者仅在结果中列出一次。

#1


6  

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.

filter()与Books表进行JOIN并生成bestseller == True的所有行。 distinct()确保每个作者仅在结果中列出一次。