You need to enable JavaScript to run this app. 如何在Django中基于多对多字段实现GROUP BY统计产品总数量
优惠活动
大模型
产品
解决方案
定价
更多

如何在Django中基于多对多字段实现GROUP BY统计产品总数量

实现步骤

  1. 先导入Django ORM所需的聚合工具
from django.db.models import Sum, F
  1. 执行查询(完全对齐给出的SQL逻辑,且通过Orders模型实现)
stat_result = Orders.objects.values(
    name=F("product__name")
).annotate(
    qte=Sum("ordersquantities__quantity")
).order_by("-qte")

结果说明

返回的stat_result是可迭代的QuerySet,每个元素为字典,格式完全匹配对应SQL的查询输出:

# 示例输出
<QuerySet [{'name': '产品A', 'qte': 120}, {'name': '产品B', 'qte': 86}, ...]>

如果不需要严格对齐SQL的字段别名,也可以使用简化写法:

stat_result = Orders.objects.values(
    "product__name"
).annotate(
    total_qty=Sum("ordersquantities__quantity")
).order_by("-total_qty")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 08:54:07