Django:按月/年分组的日期属性的总和
我想将此查询从 SQL 放到 Django:
"select date_format(date, '%Y-%m') as month, sum(quantity) as hours from hourentries group by date_format(date, '%Y-%m') order by date;"
导致问题的部分是聚合时按月分组。我尝试了这个(这似乎合乎逻辑),但它不起作用:
HourEntries.objects.order_by("date").values("date__month").aggregate(Sum("quantity"))
I'd like to put this query from SQL to Django:
"select date_format(date, '%Y-%m') as month, sum(quantity) as hours from hourentries group by date_format(date, '%Y-%m') order by date;"
The part that causes problem is to group by month when aggregating. I tried this (which seemed logical), but it didn't work :
HourEntries.objects.order_by("date").values("date__month").aggregate(Sum("quantity"))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
aggregate
只能生成一个聚合值。您可以通过以下查询获取当月的小时总数。
因此,要获取 HourEntry 所有月份的聚合值,您可以循环数据库中所有月份的查询集。但最好使用原始sql。
aggregate
can only generate one aggregate value.You can get the aggregate sum of Hours of the current month by the following query.
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.
我猜想在使用
values("date__month")
后您无法聚合“数量”,因为这只会在查询集中留下“日期”和“月份”。I guess you cannot aggregate on "quantity" after using
values("date__month")
, as this leaves only "date" and "month" in the QuerySet.