如何在Django中计算博客类别并将其显示在模板中

时间:2018-11-25 14:04:38

标签: javascript python html django

Django的一个新功能正在开发一个博客,该博客具有post_list,category_detail和post detail功能 在呈现blog.html的post_list函数中,我想显示python和硬件的博客类别以及该类别中的帖子总数 我尝试了显示错误方式的方法,因为在python类别中应该有6个帖子,在硬件类别see the picture here 中应该有1个帖子,请检查代码并提供帮助

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 %}

1 个答案:

答案 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 %}