Sandra
Sandra

Reputation: 167

Djange Queryset .annotate - Add 45 days to a date field

I want to display my_date + 345 days using Django .annotate.

In the code below,

date_plus_1=ExtractYear('my_date')+1, 

works fine to give me a the year plus one, but I want the date plus 345 days.

CODE:

.annotate(
    date_plus_1=ExtractYear('my_date')+1,
    #date_plus_345=('my_date' + timedelta(days=345)),
)

When I remove the # (in the code), my page will not generate.

After searching around, I also tried this:

date_plus_345=ExpressionWrapper(F('my_date') + timedelta(days=345)),

but that did not work either.

What is the correct way to use timedelta within .annotate?

Upvotes: 8

Views: 2476

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477759

You forgot to specify the output_field=… parameter of the ExpressionWrapper expression [Django-doc]:

from datetime import timedelta
from django.db.models import DateTimeField, ExpressionWrapper, F

MyModel.objects.annotate(
    date_plus345=ExpressionWrapper(
        F('creation_date') + timedelta(days=345),
        output_field=DateTimeField()
    )
)

Upvotes: 13

Related Questions