10

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?

2
  • what is the field type of date and end ? Is both are DateTimeField in models? Can you show the relevant parts of the models? Commented Jun 14, 2019 at 7:01
  • @JPG date is DateField and end is TimeField. Commented Jun 14, 2019 at 7:02

2 Answers 2

15

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()
    )
)
Sign up to request clarification or add additional context in comments.

1 Comment

Won't work in case your interval depends on other table columns.
5

For people coming here and looking for a way to add interval depending on a column from the table itself, you can proceed as following:

Edit 12 Dec. 2024: The snippet is for Postgresql

class MyModel(models.Model):
    quantity = ...
    created = ...


class Interval(Func):
    function = "INTERVAL"
    template = "(%(expressions)s * %(function)s '1' DAY)"

...

MyModel.objects.annotate(
    expiry_date=ExpressionWrapper(
        F("created") + Interval("quantity"),
        output_field=models.DateTimeField(),
    )
)

The code above will add N days to the created date field, where N is the quantity field.

2 Comments

Suggested template generates this SQL expression: (created + (quantity * INTERVAL '1' DAY)) AS expiry_date which doesn't work on MySQL. I modified it like that: %(function)s %(expressions)s DAY And it generates the SQL expression: (created + INTERVAL quantity DAY) AS expiry_date which seems to work on MySQL, don't know for other RDMS
This is for postgres, sorry I should have mentionned it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.