本文介绍了Django过滤具有至少一个多对多且具有value属性的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Django的ORM进行复杂的过滤.

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

型号:

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?

查询:

best_authors = Author.objects.filter(<relevant filter>)


根据文档,以下内容应该起作用:

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()

filter() Books 表执行 JOIN ,并生成 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.

这篇关于Django过滤具有至少一个多对多且具有value属性的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!