且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Django:对按月/年分组的日期属性求和

更新时间:2023-01-29 20:48:20

汇总只能生成一个汇总值。

aggregate can only generate one aggregate value.

您可以获取小时的汇总

from datetime import datetime
this_month = datetime.now().month
HourEntries.objects.filter(date__month=this_month).aggregate(Sum("quantity"))

因此,要获取HourEntry所有月份的合计值,可以在db中遍历所有月份的查询集。但***使用原始sql。

So, to obtain the aggregate values of HourEntry's all the months, you can loop over the queryset for all the months in the db. But it is better to use the raw sql.

HourEntries.objects.raw("select date_format(date, '%Y-%m') as month, sum(quantity) as hours from hourentries group by date_format(date, '%Y-%m') order by date;")