Answers for "how to count post by category django"

1

how to count post by category django

#views.py
from django.db.models import Count
# You should change post in Count function based on your model.
categories = Category.objects.all().annotate(posts_count=Count('post'))

#Then you will have access to number of posts for each category:
for category in categories:
    print(category.posts_count)

#in your template
{% for category in categories %}
      <p>Number of posts: {{category.posts_count}}</p>
{% endfor %}
Posted by: Guest on December-21-2020

Code answers related to "how to count post by category django"

Python Answers by Framework

Browse Popular Code Answers by Language