python - Django 。如何从相关模型注释对象计数

标签 python django django-queryset

假设我有一个模型评论和另一个模型答案。我想查询所有评论,但也在查询中包括每个评论的答案数量。我认为 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/

相关文章:

python - 无法在 python 2.7 中导入 boto3

python - Pandas:添加新的计算(分数)行

python - Django中邮箱验证的实现

python - PyVista:为什么回调第二次只绘制 3d 实体而不是 2d 实体?

python - 用于公开图像的 Django REST API

django - 如何将值从 get_queryset() 传递到 get_context_data()

Django 在 ManyToMany 计数上过滤模型?

django - 如何合并多个查询集并删除重复项?

python - Django ,南 : I get a warning with key length while indexing

python - 我需要将 virtualenv 与 Vagrant 一起使用吗?