姜戈。如何从相关模型注释对象计数
Django. How to annotate a object count from a related model
假设我有一个模型评论和另一个模型答案。我想查询所有评论,但也在查询中包括每个评论的答案数量。我认为 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(...?)
我不确定如何注释每条评论的 Count
个答案。也就是FK字段的每条评论指向多少答案comment
。有可能吗?有没有更好的办法?只在管理器上写一个方法会更好吗?
您需要使用a Count
aggregation:
from django.db.models import Count
comments = Comments.objects.annotate(num_answers=Count('answers'))
假设我有一个模型评论和另一个模型答案。我想查询所有评论,但也在查询中包括每个评论的答案数量。我认为 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(...?)
我不确定如何注释每条评论的 Count
个答案。也就是FK字段的每条评论指向多少答案comment
。有可能吗?有没有更好的办法?只在管理器上写一个方法会更好吗?
您需要使用a Count
aggregation:
from django.db.models import Count
comments = Comments.objects.annotate(num_answers=Count('answers'))