在Django Queryset中使用时间戳分组

时间:2018-06-29 11:12:30

标签: python django postgresql

我有一个模型,其中存储每个条目并存储其创建时间。时间不是日期时间对象,而是时间戳。模型的时间戳字段如下所示:

  

logged_at = models.CharField(_('log time'),max_length = 128,   default = time.time)

如果上面的字段是日期时间字段,那么我可以编写一个查询,该查询可以使用日期时间字段将记录分组:

MyModel.objects.filter(type_='in').annotate(in_time=RawSQL('(date(logged_at))', [])).values('in_time', 'name').annotate(count=Count('name'))

但是我无法以相同的方式查询timesatmp字段,这给了我错误date/time field value out of range

我还尝试过使用to_timestamp仍然无法成功

MyModel.objects.filter(type_='in').annotate(in_time=RawSQL('(date(to_timestamp(logged_at)))', [])).values('in_time', 'name').annotate(count=Count('name'))

错误:函数to_timestamp(字符变化)不存在

我正在使用的数据库是 Postgres

1 个答案:

答案 0 :(得分:0)

正如@Willem在评论中提到的那样,不得将时间戳记存储在CharField中。因此,我们可以尝试在运行时更改字段类型,如下所示。

MyModel.objects.filter(type_='in').annotate(in_time=RawSQL('(date(to_timestamp(logged_at::float)))', [])).values('in_time', 'name').annotate(count=Count('name')) 

在上述查询中,我已将logged_at的类型更改为float,对我来说效果很好,您也可以将其更改为int