You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django:如何对QuerySet字典值求和及分隔数据用于图表

Django 月度统计求和与图表数据处理方案

一、计算年度总条目数

推荐在后端处理逻辑,效率更高:

  • 方式1:基于现有分组结果求和
    直接遍历已有的stats查询集计算总和:

    total_entries = sum(item['total'] for item in stats)
    

    把total_entries传入模板后,直接用{{ total_entries }}就能展示26这个结果。

  • 方式2:直接查询总条数(更高效)
    不需要先分组再求和,直接统计符合条件的所有条目数:

    total_entries = EntryMonitoring.objects.filter(student_id=user).count()
    

如果非要在模板内处理(不推荐,逻辑尽量放后端),可以用变量累加:

{% with total=0 %}
    {% for obj in stats %}
        {% obj.total as current %}
        {% total|add:current as total %}
    {% endfor %}
    年度总条目数:{{ total }}
{% endwith %}

二、分隔月度数据用于图表

1. 后端整理成图表可用的格式

把月份和对应条目数分别提取成列表,方便前端图表(如Chart.js、ECharts)调用:

# 格式化月份为"YYYY-MM"格式,比如"2024-03"
month_labels = [item['month'].strftime("%Y-%m") for item in stats]
# 提取月度条目数列表
monthly_counts = [item['total'] for item in stats]

将month_labels和monthly_counts传入模板后,在JS中直接使用:

<script>
    const monthLabels = {{ month_labels|safe }};
    const monthlyCounts = {{ monthly_counts|safe }};
    // 示例:用Chart.js生成柱状图
    new Chart(document.getElementById('monthly-chart'), {
        type: 'bar',
        data: {
            labels: monthLabels,
            datasets: [{
                label: '月度条目数',
                data: monthlyCounts,
                backgroundColor: 'rgba(75, 192, 192, 0.2)'
            }]
        }
    });
</script>

2. 页面上直接分隔展示月度数据

如果只是要在页面文本中分隔显示,用模板标签判断是否为最后一条:

{% for obj in stats %}
    {{ obj.month|date:"Y年m月" }}:{{ obj.total }}条
    {% if not forloop.last %},{% endif %}
{% endfor %}

最终会显示为:2024年03月:25条,2024年04月:1条

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 18:52:08