假设我有一个模型评论和另一个模型答案。我想查询所有评论,但也在查询中包括每个评论的答案数量。我认为 annotate()
在这种情况下会很有用,但我只是不知道如何写下来。文档写道:
New in Django 1.8: Previous versions of Django only allowed aggregate functions to be used as annotations. It is now possible to annotate a model with all kinds of expressions.
所以。这是我的模型示例:
class Comments(models.Model):
...
class Answers(models.Model):
comment = models.ForeignKey(Comments)
这是一个示例查询:
queryset = Comments.objects.all().annotate(...?)
我不确定如何注释每个评论的答案的计数
。即FK字段comment
上的每条评论指向多少个答案。有可能吗?有没有更好的办法?只在管理器上写一个方法会更好吗?
最佳答案
您需要使用 a Count
aggregation :
from django.db.models import Count
comments = Comments.objects.annotate(num_answers=Count('answers'))
关于python - Django 。如何从相关模型注释对象计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33356152/