Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django expression DateTime and Integer seconds

I want to annotate the difference between a DateTime and an Integer (seconds) on a legacy MySQL DB (so there is no chance to change the IntegerField to a DurationField) with Django 1.11

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())
)

This would work, if uptime was a DurationField(), but won't work with an integer. So I tried converting the seconds to a timedelta

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

which gives me

AttributeError at ...

'CombinedExpression' object has no attribute 'split'

Is there a way to calculate with a DateTimeField() and a IntegerField() in a query expression?

like image 360
masterfloda Avatar asked Jun 18 '26 17:06

masterfloda


1 Answers

I found a solution: Convert the integer to a duration using the ExpressionWrapper. As I am getting seconds and a DurationField() is Microseconds, I have to multiply them by 1,000,000.

last_reboot=ExpressionWrapper(
    F('last_report') - ExpressionWrapper(
        F('uptime') * 1000000,
        output_field=DurationField()
    ),
    output_field=DateTimeField()
)
like image 108
masterfloda Avatar answered Jun 20 '26 08:06

masterfloda



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!