我正在尝试从MySQL
数据库中获取值,并根据月/日期/年使用GroupBy
。我的数据库的日期格式为unixtimestamps(int(10))
,我正在尝试在日期上使用GroupBy
。
当我使用从数据库表创建模型的默认方式创建模型时,列的生成类型为CharField
。我为time_start
和time_end
创建了一个自定义字段。
模型类别:
class LinuxJobTable(models.Model):
time_start = UnixTimestampField()
time_end = UnixTimestampField()
id_group = models.IntegerField()
mem_req = models.IntegerField()
自定义字段代码:
class UnixTimestampField(models.DateField):
def db_type(self, connection):
return datetime;
# Hopefully used to convert database values to Python format
def from_db_value(self, value, connection, test, prepared=False):
import pytz
from pytz import timezone
if value is None:
return value
localtz = timezone('US/Eastern')
print "in from_DB_VALUE:",value
conv_date = datetime.fromtimestamp(int(value))
print conv_date
return conv_date
def get_prep_value(self, value):
return int(value.strftime('%s'))
ViewClass代码:
class jobUsageApiView(generics.ListAPIView):
todays_date = datetime.today().replace(hour=0, minute=0, second=0)
min_pub_date_time = datetime.combine(todays_date, time.min)
max_pub_date_time = datetime.combine(todays_date, time.max)
queryset = LinuxJobTable.objects.filter(time_start__range=(min_pub_date_time, max_pub_date_time)).annotate(Count('id_job'));
# queryset = LinuxJobTable.objects
# .filter(time_start__range=(min_pub_date_time, max_pub_date_time))
# .values('time_start').annotate(Count('id_job'));
serializer_class = JobUsageSerializer
如果我不使用截断功能。它返回正确的结果为:
但是当我尝试按日期对它们进行分组时,截断函数将返回null
。
当我将queryset更改为:
queryset = LinuxJobTable.objects
.filter(time_start__range=(min_pub_date_time, max_pub_date_time))
.annotate(time_start2=TruncDate('time_start'))
.annotate(Count('id_job'))
它将日期截断为null
: