Django. How to annotate a object count from a related model

不羁岁月 提交于 2020-05-15 02:15:46

问题


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. The docs write that:

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.

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. That is, how many answers point to each comment on the FK field comment. Is it even possible? is there a better way? Is it better to just write a method on the manager?


回答1:


You need to use a Count aggregation:

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


来源:https://stackoverflow.com/questions/33356152/django-how-to-annotate-a-object-count-from-a-related-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!