我想用Django 1.11注释遗留MySQL数据库上的DateTime和Integer(秒)之间的区别(因此没有机会将IntegerField更改为DurationField)
Report(Model):
# time the report was sent
time = DateTimeField()
# seconds since the last reboot
uptime = IntegerField()
MyModel.objects.all().annotate(
last_report=Max(time),
last_reboot=ExpressionWrapper(F('last_report') - F('uptime')), output_field=DateTimeField())
)
如果uptime
是DurationField(),但是不能使用整数,这将有效。所以我尝试将秒转换为timedelta
last_reboot=ExpressionWrapper(
F('last_report') - F(timezone.timedelta(seconds=1)*F('uptime')),
output_field=DateTimeField()
)
这给了我
属性错误在......
'CombinedExpression'对象没有属性'split'
有没有办法在查询表达式中使用DateTimeField()和IntegerField()进行计算?
我找到了一个解决方案:使用ExpressionWrapper
将整数转换为持续时间。因为我得到秒,而DurationField()
是微秒,我必须将它们乘以1,000,000。
last_reboot=ExpressionWrapper(
F('last_report') - ExpressionWrapper(
F('uptime') * 1000000,
output_field=DurationField()
),
output_field=DateTimeField()
)
以前,我做了类似下面的事情......可能对其他人有用。
.annotate(timestamp=RawSQL('DATE(milisecond_datetimestamp, \'unixepoch\')',[]))
和另一个查询,我必须将日期整数字段转换为小时
.annotate(hour=Round(F('milisecond_datetimestamp') % (3600 * 24) /3600))
对于Round
,你必须定义如下的SQL函数
class Round(Func):
function= 'ROUND'