Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django annotate add interval to date

I am using postgres database with Django 2.2. I need to combine date and time field in model and add an interval of one day in it. I have done first part like this.

Model.objects.annotate(
    end_dt=models.ExpressionWrapper(
        models.F('date') + models.F('end'),
        output_field=models.DateTimeField()
    )
)

Now I have to add 1 day to end_dt. I have done this with plain sql like this.

SELECT 
       "db_shift"."id",
       (("db_shift"."date" + "db_shift"."end") + INTERVAL '1 day') AS "end_dt"
FROM 
     "db_shift";

How can I achieve this using django ORM? Or is it even achievable?

like image 657
Nafees Anwar Avatar asked Jun 14 '19 06:06

Nafees Anwar


Video Answer


1 Answers

After a bit of experimentation I have found that adding timedelta from datetime works just fine :)

import datetime


Model.objects.annotate(
    end_dt=models.ExpressionWrapper(
        models.F('date') + models.F('end') + datetime.timedelta(days=1),
        output_field=models.DateTimeField()
    )
)
like image 120
Nafees Anwar Avatar answered Sep 18 '22 00:09

Nafees Anwar