简体   繁体   English

Django的。 如何从相关模型中注释对象计数

[英]Django. How to annotate a object count from a related model

lets say I have a model Comments and another model Answers. 让我说我有一个模型评论和另一个模型答案。 I want to query all comments but also include in the query the number of answers each comment has. 我想查询所有注释,但也在查询中包含每个注释的答案数。 I thought annotate() would be useful in this case, but I just don't know how to write it down. 我认为annotate()在这种情况下会很有用,但我只是不知道如何写下来。 The docs write that: 文档写道:

New in Django 1.8: Previous versions of Django only allowed aggregate functions to be used as annotations. Django 1.8中的新功能:以前版本的Django只允许将聚合函数用作注释。 It is now possible to annotate a model with all kinds of expressions. 现在可以使用各种表达式来注释模型。

So. 所以。 This is an example of my models: 这是我的模型的一个例子:

class Comments(models.Model):
   ...

class Answers(models.Model):
   comment = models.ForeignKey(Comments)

And this is an example query: 这是一个示例查询:

queryset = Comments.objects.all().annotate(...?)

I'm not sure how to annotate the Count of answers each comment has. 我不确定如何注释每个评论的答案Count That is, how many answers point to each comment on the FK field comment . 也就是说,有多少答案指向FK字段comment每个comment Is it even possible? 它甚至可能吗? is there a better way? 有没有更好的办法? Is it better to just write a method on the manager? 在经理上写一个方法更好吗?

You need to use a Count aggregation : 您需要使用Count聚合

from django.db.models import Count
comments = Comments.objects.annotate(num_answers=Count('answers'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM