# models.py
from django.db import models
class Category(models.Model):
name = models.CharField(max_length=255)
class Post(models.Model):
title = models.CharField(max_length=255)
content = models.TextField()
category = models.ForeignKey(Category, on_delete=models.CASCADE)
# views.py
from django.shortcuts import render
from django.db.models import Count
from .models import Category, Post
def category_post_count(request):
categories_with_count = Category.objects.annotate(post_count=Count('post'))
return render(request, 'your_template.html', {'categories_with_count': categories_with_count})
<!-- your_template.html -->
{% for category in categories_with_count %}
<h2>{{ category.name }}</h2>
<p>Post Count: {{ category.post_count }}</p>
{% endfor %}
# urls.py
from django.urls import path
from .views import category_post_count
urlpatterns = [
path('category_post_count/', category_post_count, name='category_post_count'),
]