Django中无法显示分类名称及对应文章数量的问题
解决方法
方案一:调整Post查询,直接获取分类名称
修改blog/views.py的查询逻辑,通过外键关联字段获取分类名称并分组统计:
from django.db.models import Count def searchView(request): # 按分类名称分组,统计对应文章数量 statistics = Post.objects.values('cid__category_name').annotate(num_articles=Count('cid')).order_by('-num_articles') return render(request, 'blog/search.html', {'statistics': statistics})
然后更新blog/search.html中的模板变量,替换成分类名称字段:
{% for stat in statistics %} <tr> <td> {{ stat.cid__category_name }} </td> <td> {{ stat.num_articles }} </td> </tr> {% endfor %}
方案二:从Category模型反向查询(更推荐)
直接从分类模型出发,利用反向关联统计文章数,能拿到完整的分类对象,后续扩展更灵活:
修改blog/views.py:
from django.db.models import Count from .models import Category def searchView(request): # 统计每个分类下的文章数,可按需过滤已批准文章 statistics = Category.objects.annotate(num_articles=Count('post')).order_by('-num_articles') # 如果仅统计已审核通过的文章,使用以下语句: # statistics = Category.objects.annotate(num_articles=Count('post')).filter(post__approved=True).order_by('-num_articles') return render(request, 'blog/search.html', {'statistics': statistics})
更新blog/search.html模板,直接调用分类名称属性:
{% for stat in statistics %} <tr> <td> {{ stat.category_name }} </td> <td> {{ stat.num_articles }} </td> </tr> {% endfor %}
补充说明
- 方案二的优势在于能获取完整的分类对象,后续如果需要使用分类ID等其他属性,无需修改查询逻辑;
order_by('-num_articles')用于按文章数量倒序排列,可根据需求调整排序规则或移除。
内容的提问来源于stack exchange,提问作者Sudipta Bhatta
相关产品推荐
相关产品推荐

