You can use the annotate()
method along with the Count
aggregation function of the Django ORM to find and store the number of objects stored in the QuerySet.
from django.db.models import Count
...
"categories": Category.objects.annotate(post_count=Count('post')),
The Count('post') aggregates the number of Post objects related to each Category through the ForeignKey.
Then you may refer to your own annotation, post_count
, in your templates:
<ul>
{% for category in categories %}
<li>
<a href="{{ category.get_absolute_url }}">{{ category.name }}</a>
({{ category.post_count }} posts)
</li>
{% endfor %}
</ul>
Don't worry about the replacement of the all()
method, there's no difference really - What is difference between objects.all().annotate and objects.annotate?