Django + PostgreSQL在datetimefield上按日期分组 [英] Django + PostgreSQL group by date on datetimefield

查看:92
本文介绍了Django + PostgreSQL在datetimefield上按日期分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型,其中有一个datetimefield,我想在按日期分组时进行注释。

I have a model which has a datetimefield that I'm trying to annotate on grouping by date.

例如:

order_totals = Transfer.objects.filter(created__range=[datetime.datetime.combine(datetime.date.today(), datetime.time.min) + datetime.timedelta(days=-5), datetime.datetime.combine(datetime.date.today(), datetime.time.max)]).values('created').annotate(Count('id'))

上述问题是它按日期时间字段的秒/毫秒而不是日期进行分组。

The problem with the above is it groups by every second/millisecond of the datetime field rather then just the date.

我该怎么做?

推荐答案

您应该能够解决此问题通过使用QuerySet.extra并向查询中添加列

You should be able to solve this by using QuerySet.extra and add a column to the query

例如。

qs.filter(...).extra(select={'created_date': 'created::date'}).values('created_date')

这篇关于Django + PostgreSQL在datetimefield上按日期分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆