如何在 django 中过滤查询集的多对多

Posted

技术标签:

【中文标题】如何在 django 中过滤查询集的多对多【英文标题】:How to filter the ManyToMany of a queryset in django 【发布时间】:2020-04-30 20:00:46 【问题描述】:

我有两个模型,问题及其答案,我想获取所有问题以及一个单一答案,即具有该问题的支持者人数上限。如何在 Queryset 中获取此结果(我将对结果进行分页,以便使用 queryset 来简化流程)

class Question(models.Model):
    question = models.CharField(max_length = 128)
    asker = models.ForeignKey(CustomUser, on_delete = models.CASCADE, related_name="asked_questions")
    requested = models.ManyToManyField(CustomUser, related_name="answer_requests")
    followers = models.ManyToManyField(CustomUser, related_name="followed_questions")
    topics = models.ManyToManyField(Topic, related_name="questions")
    url = models.CharField(max_length = 150)
    created_at = models.DateTimeField(auto_now_add = True, blank = True)


    def __str__(self):
        return self.question

class Answer(models.Model):
    answer = models.TextField()
    author = models.ForeignKey(CustomUser, on_delete = models.CASCADE, related_name="written_answers")
    question = models.ForeignKey(Question, on_delete = models.CASCADE, related_name="answers")
    upvoters = models.ManyToManyField(CustomUser, related_name="upvoted_answers")
    created_at = models.DateTimeField(auto_now_add = True, blank = True)

【问题讨论】:

【参考方案1】:

使用subquery expression 尝试这样的操作

from django.db.models import Count, Subquery, OuterRef

answer_subquery = Answer.objects.filter(question=OuterRef('pk')).annotate(upvotes=Count('upvoters')).order_by('-upvotes')

questions = Question.objects.annotate(answer=Subquery(answer_subquery.values('answer')[:1]))

【讨论】:

超级有帮助。非常感谢!

以上是关于如何在 django 中过滤查询集的多对多的主要内容,如果未能解决你的问题,请参考以下文章

如何在引导选项卡块中按 django 模板中的多对多字段过滤对象

根据特定的多对多关系过滤 Django 查询集

如何过滤和访问 Django QuerySet 中的多对多字段?

过滤后更新 Django 的多对多

如何在 django 中处理未保存的多对多关系?

Django,在 self 类中的多对多关系中,我如何在 ORM 方面相互引用?