【发布时间】:2026-01-18 01:20:06
【问题描述】:
如何在不使用额外的情况下按月计算总数?
我目前正在使用:
- django 1.8
- postgre 9.3.13
- Python 2.7
示例。
到目前为止我所尝试的。
#Doesn't work for me but I don't mind because I don't want to use extra
truncate_month = connection.ops.date_trunc_sql('month','day')
invoices = Invoice.objects.filter(is_deleted = False,company = company).extra({'month': truncate_month}).values('month').annotate(Sum('total'))
----
#It works but I think that it's too slow if I query a big set of data
for current_month in range(1,13):
Invoice.objects.filter(date__month = current__month).annotate(total = Sum("total"))
还有这个,答案似乎很好,但我无法导入 TruncMonth 模块。
Django: Group by date (day, month, year)
附:我知道这个问题已经被问过多次,但我没有看到任何答案。
谢谢!
解决方案:
感谢@Vin-G 的回答。
【问题讨论】:
-
请展示您为此尝试过的内容
-
你可以看到这个例子来获得灵感*.com/a/8746532/2581266
-
@PapoucheGuinslyzinho 我已经测试过了,但我似乎无法导入 TruncMonth 模块。
-
你有哪个版本的 django?
-
django 1.8 但 tback 说它适用于 1.10 及更高版本。
标签: python django postgresql