how to count post by category django

Solutions on MaxInterview for how to count post by category django by the best coders in the world

showing results for - "how to count post by category django"
Avalon
28 Nov 2020
1#views.py
2from django.db.models import Count
3# You should change post in Count function based on your model.
4categories = Category.objects.all().annotate(posts_count=Count('post'))
5
6#Then you will have access to number of posts for each category:
7for category in categories:
8    print(category.posts_count)
9
10#in your template
11{% for category in categories %}
12      <p>Number of posts: {{category.posts_count}}</p>
13{% endfor %}
14