You need to enable JavaScript to run this app. 如何在Django模板标签中实现分类使用次数的Groupby统计?
优惠活动
大模型
产品
解决方案
定价
更多

如何在Django模板标签中实现分类使用次数的Groupby统计?

你可以直接用Django ORM自带的annotate聚合方法实现,不需要复杂的数据库操作,也不用额外写循环逻辑。

操作步骤

  1. 先在你的模板标签文件头部引入聚合计数函数
from django.db.models import Count
  1. 修改Category的查询语句,给每个分类对象追加关联资源的计数字段
    这里默认你的博客文章模型是Post,且通过外键关联到Category,如果你的外键设置了related_name,把Count的参数换成你设置的related_name值即可。
    修改后的完整模板标签代码如下:
@register.inclusion_tag('blog/components/categories_list.html',
                        takes_context=True)
def categories_list(context):
    # annotate会给每个category对象新增post_count属性,存储该分类关联的文章总数
    categories = Category.objects.annotate(post_count=Count('post'))
    return {
        'request': context['request'],
        'categories': categories,
        # 如果还需要统计总分类数可以保留该字段,不需要可以直接删除
        'total_categories': categories.count()
    }
  1. 模板中直接调用计数字段即可
    遍历分类列表时,直接读取每个分类对象的post_count属性就能拿到对应分类的使用次数:
<ul>
{% for category in categories %}
    <li>{{ category.name }}:共 {{ category.post_count }} 篇文章</li>
{% endfor %}
</ul>

额外拓展

如果需要过滤掉没有文章的空分类,只需要在查询语句后追加过滤条件即可:

categories = Category.objects.annotate(post_count=Count('post')).filter(post_count__gt=0)

这个聚合操作是ORM直接转换为SQL的分组查询执行,执行效率很高,没有额外的性能开销。

内容的提问来源于stack exchange,提问作者yung peso

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.12 00:36:03