【问题标题】:Django expression DateTime and Integer secondsDjango 表达式 DateTime 和 Integer seconds
【发布时间】:2018-03-01 21:51:07
【问题描述】:

我想用 Django 1.11 注释旧 MySQL DB 上的 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(),这将起作用,但不适用于整数。所以我尝试将秒转换为时间增量

last_reboot=ExpressionWrapper(
    F('last_report') - F(timezone.timedelta(seconds=1)*F('uptime')),
    output_field=DateTimeField()
)

这给了我

AttributeError at ...

'CombinedExpression' 对象没有属性'split'

有没有办法在查询表达式中使用 DateTimeField() 和 IntegerField() 进行计算?

【问题讨论】:

    标签: python django django-models django-queryset


    【解决方案1】:

    我找到了解决方案:使用ExpressionWrapper 将整数转换为持续时间。当我得到秒并且DurationField() 是微秒时,我必须将它们乘以 1,000,000。

    last_reboot=ExpressionWrapper(
        F('last_report') - ExpressionWrapper(
            F('uptime') * 1000000,
            output_field=DurationField()
        ),
        output_field=DateTimeField()
    )
    

    【讨论】:

      【解决方案2】:

      以前,我做了类似下面的事情......可能对其他人有用。

      .annotate(timestamp=RawSQL('DATE(milisecond_datetimestamp, \'unixepoch\')',[])) 
      

      还有另一个查询,我必须将日期整数字段转换为小时

      .annotate(hour=Round(F('milisecond_datetimestamp') % (3600 * 24) /3600)) 
      

      对于Round,您必须定义如下 SQL 函数

      class Round(Func):
          function= 'ROUND'
      

      【讨论】:

      • 我尽量避免使用RawSQLextra()。但是Round 方法还不错。我还是会选择ExpressionWrapper。不过谢谢!
      猜你喜欢
      • 2013-07-15
      • 1970-01-01
      • 2013-01-24
      • 1970-01-01
      • 2012-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多