views.py
def post_list(request):
object_list=Post.objects.filter(status='Published').order_by("-created")
recent_post=object_list[:4]
category_list_count=Post.objects.annotate(num_category=Count('Category'))
page = request.GET.get('page', 1)
paginator = Paginator(object_list, 3)
try:
items = paginator.page(page)
except PageNotAnInteger:
items = paginator.page(1)
except EmptyPage:
items = paginator.page(paginator.num_pages)
context={
'items':items,
'recent_post':recent_post,
'category_list_count':category_list_count,
}
return render(request,"blog.html",context)
blog.html
<div class="widget">
<h3 class="badge">CATEGORIES</h3>
{% for obj in category_list_count %}
<ul>
<li><a href="{% url 'category_detail' slug=obj.Category.slug %}">{{obj.Category}}</a> <span class="badge">{{obj.num_category}}</span>
</li>
</ul>
{% endfor %}
答案 0 :(得分:0)
尝试一下:
# You should change post in Count function based on your model.
categories = Category.objects.all().annotate(posts_count=Count('post'))
然后,您将可以访问每个类别的帖子数量:
for category in categories:
print(category.posts_count)
在您的模板中:
{% for category in categories %}
<p>Number of posts: {{category.posts_count}}</p>
{% endfor %}