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

如何在Django查询集中按Product和Condition分组求和Quantity

嘿,这事儿不难!要把相同product和condition的条目合并,对quantity求和,用Django的聚合查询就能轻松实现,咱这么来:

实现步骤

1. 核心聚合查询代码

假设你的模型名为Inventory,在视图、模型管理器或者shell里可以这么写:

from django.db.models import Sum

# 按product和condition分组,对quantity求和
aggregated_results = Inventory.objects.values('product', 'condition').annotate(total_quantity=Sum('quantity')).order_by('product', 'condition')

代码解释:

  • values('product', 'condition'):告诉Django要按这两个字段的值进行分组
  • annotate(total_quantity=Sum('quantity')):对每个分组内的quantity字段做求和运算,结果存到total_quantity字段里
  • order_by('product', 'condition'):让结果按产品和状态排序,看起来更规整

2. 输出成目标表格格式

如果要把结果输出成你想要的表格样式,比如在控制台打印或者前端展示,可以遍历结果拼接成表格:

# 打印表头
print("| Product | Condition | Quantity |")
print("+---------+-----------+----------+")
# 遍历聚合后的结果
for item in aggregated_results:
    print(f"| {item['product']:<7} | {item['condition']:<9} | {item['total_quantity']:<8} |")

运行后就能得到你期望的结果:
| Product | Condition | Quantity |
+---------+-----------+----------+
| A | new | 9 |
| A | old | 3 |
| B | new | 6 |
| B | old | 6 |

3. 扩展技巧

如果需要先过滤数据再聚合,比如只处理某个产品的数据,可以在查询链前面加上filter:

# 只聚合产品A的数据
a_results = Inventory.objects.filter(product='A').values('product', 'condition').annotate(total_quantity=Sum('quantity'))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:54:22