如何在Django ORM中实现多聚合字段求和相乘的分组查询
Django ORM 实现对应查询的方案
首先导入需要的ORM工具类:
from django.db.models import Sum, F, Value from django.db.models.functions import Coalesce
基础查询写法(完全匹配你提供的SQL逻辑)
query_result = Product.objects.values("category")\ .annotate( sum_price = Sum("price"), sum_inventory = Sum("productinventory__inventory") )\ .annotate( calculate_result = F("sum_price") * F("sum_inventory") )
逻辑说明:
values("category")自动对应GROUP BY category逻辑- 因为你没有给一对一关系设置
related_name,所以反向关联ProductInventory默认用小写类名productinventory作为前缀,ORM访问关联字段inventory写法为productinventory__inventory,默认走左连接逻辑,和你要求的LEFT JOIN完全匹配 - 第一个
annotate分别计算分组后的价格总和、库存总和 - 第二个
annotate用F表达式实现两个聚合结果的乘法运算 - 最终返回的结果每条都是字典格式,包含
category、sum_price、sum_inventory、calculate_result四个字段,和原生SQL返回结果一致
空值兼容优化
如果存在没有对应库存记录的商品,sum_inventory会返回None,最终计算结果也会为None,如果需要把这种场景的库存按0计算,可以用Coalesce处理空值:
query_result = Product.objects.values("category")\ .annotate( sum_price = Sum("price"), sum_inventory = Coalesce(Sum("productinventory__inventory"), Value(0)) )\ .annotate( calculate_result = F("sum_price") * F("sum_inventory") )
内容的提问来源于stack exchange,提问作者Github Copilot
相关产品推荐
相关产品推荐

