Skip to content
Advertisement

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?

Advertisement

Answer

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()
    )
)
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement