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

Django按月统计订单总数问题:重复分组结果修正

解决Django按月统计订单总数重复的问题

问题根源

你的CartOrder模型中vendor是多对多字段,执行查询时Django会关联多对多表返回数据,同一个订单会因关联多个vendor被多次输出,导致分组统计时同一月份的订单被拆分成多条记录。

修复方案

在统计时给Count添加distinct=True参数,统计唯一的订单ID:

修改后的views.py代码:

import calendar
from django.db.models.functions import ExtractMonth
from django.db.models import Count

orders = CartOrder.objects.annotate(month=ExtractMonth('date')).values('month').annotate(count=Count('id', distinct=True)).values('month','count')

print(orders)

也可以先通过distinct()获取唯一订单记录,再做分组统计:

orders = CartOrder.objects.distinct().annotate(month=ExtractMonth('date')).values('month').annotate(count=Count('id')).values('month','count')

说明

  • Count('id', distinct=True)会忽略重复的订单ID,确保每个订单只被统计一次,避免多对多关联带来的重复计数。
  • distinct()先去重订单记录,再分组统计,同样能避免重复数据干扰统计结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 13:33:12