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

如何在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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 14:48:04