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

如何在Django Query中按Party表的唯一party_name分组统计Sales_Transaction表的total_cost总和?

Django Query实现按Party分组统计Sales_Transaction的total_cost总和

问题的核心在于你用了aggregate()方法——它是对整个QuerySet做全局聚合,所以只会返回所有Party的总合计值。要实现按每个Party分组统计,你需要结合values()和annotate()来完成分组聚合:

正确的查询代码

from django.db.models import Sum

# 按party_name分组,统计每个分组对应的total_cost总和
party_purchase_totals = Party.objects.values('party_name').annotate(
    total_purchase=Sum('sales__salestransaction__total_cost')
).order_by('party_name')

代码解释

  1. values('party_name'):这一步告诉Django要按party_name字段对结果进行分组,是实现“每个Party单独统计”的关键。
  2. annotate(...):对每个分组(即每个唯一的party_name),计算其关联的Sales→Sales_Transaction链条中total_cost的总和,并将结果命名为total_purchase。
  3. order_by('party_name'):可选操作,用来让结果按Party名称排序,方便查看。

处理无交易的Party

如果某个Party没有任何关联的Sales或Sales_Transaction,total_purchase会返回None。你可以用Coalesce函数把它替换为0,让结果更规整:

from django.db.models import Sum, Value
from django.db.models.functions import Coalesce

party_purchase_totals = Party.objects.values('party_name').annotate(
    total_purchase=Coalesce(Sum('sales__salestransaction__total_cost'), Value(0))
).order_by('party_name')

输出成表格格式

你可以遍历查询结果来生成你需要的表格:

# 打印表头
print("| Party Name | Total Purchase |")
print("|------------|----------------|")
# 遍历每个分组结果
for item in party_purchase_totals:
    print(f"| {item['party_name']}    | {item['total_purchase']} |")

这样就能得到你期望的按Party分组的统计结果啦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 13:48:11