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

Django按公司分组求和账单金额对接Chart.js实现环形图展示

实现步骤

第一步:修改视图层查询逻辑

你需要用Django ORM的values() + annotate()组合实现按公司分组聚合总金额,直接替换home视图里的查询逻辑即可:

...
from bills.models import Bill
from django.db.models import Sum

def home(request):
    # 按关联的公司名称分组,聚合计算每个公司的账单总金额
    data = Bill.objects.values(
        'company_name__associated_company'
    ).annotate(
        total_grand_tot=Sum('grand_tot')
    ).order_by('company_name__associated_company')
    context = {
        'data': data,
    }
    return render(request, 'home.html', context)

这段查询返回的每个元素结构为{'company_name__associated_company': '公司名', 'total_grand_tot': 总金额},已经按公司去重,总金额是该公司所有账单的求和结果。

第二步:修改前端Chart.js渲染逻辑

因为返回的字段发生了变化,对应修改环形图的标签和数据取值即可:

const ctx = document.getElementById('myChart').getContext('2d');
const myChart = new Chart(ctx, {
    type: 'doughnut',
    data: {
        labels: [
            {% for item in data %} '{{ item.company_name__associated_company }}', {% endfor %}
        ],
        datasets: [{
            label: '账单总金额(美元)',
            data: [{% for item in data %} {{ item.total_grand_tot }}, {% endfor %}],
            // 剩余原有配置保持不变即可
            ...
        }]
    }
});

提示:这里把循环变量名从data改成了item避免和外层变量重名减少歧义,你也可以保持原有变量名,只要对应取值字段正确即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 16:54:03