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

如何用单条Django Queryset按金额区间分组汇总交易数据?

Django 按金额区间分组求和(单查询实现)

你当前的实现需要多次发起数据库查询,效率偏低。这种按数值范围分组统计的方式叫区间分组,可以通过Django的Case/When结合分组查询实现单条查询完成需求:

首先导入所需的模型字段和函数:

from django.db.models import Case, When, Sum, CharField

然后执行单查询分组求和:

# 给每条交易标记所属金额区间,再按区间分组求和
transactions_summary = Transactions.objects.annotate(
    amount_range=Case(
        When(amount__gt=-20, amount__lte=0, then="'0 ~ -20'"),
        When(amount__gt=-50, amount__lte=-20, then="'20 ~ -50'"),
        When(amount__gt=-75, amount__lte=-50, then="'50 ~ -75'"),
        When(amount__gt=-100, amount__lte=-75, then="'75 ~ -100'"),
        When(amount__lte=-100, then="'100 及以下'"),
        output_field=CharField(),
    )
).values('amount_range').annotate(total_amount=Sum('amount'))

结果说明

返回的transactions_summary是一个QuerySet,每个元素是包含区间名称和对应总和的字典,示例结构:

<QuerySet [
    {'amount_range': '0 ~ -20', 'total_amount': Decimal('-150.00')},
    {'amount_range': '20 ~ -50', 'total_amount': Decimal('-320.00')},
    ...
]>

这种方式只需一次数据库查询,性能远优于多次单独过滤聚合的实现。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 16:13:16