如何在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
相关产品推荐
相关产品推荐

