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

Like this is there any ways to add 40 months to the creation_date field and annotate it?

Hyz
  • 1
  • Why not make it a poperty of your `MyModel` class? – Willem Van Onsem Jun 14 '21 at 16:32
  • @WillemVanOnsem Because I need to sort my result based on that field? So if I make it a property of model MyModel to sort I have to bring all the dataset from the database to the server, right? – Hyz Jun 14 '21 at 17:21
  • but if this is each time 40 months, this means it is completely equivalent to filter on the `creation_date`. – Willem Van Onsem Jun 14 '21 at 17:22
  • @WillemVanOnsem months can be change based on some conditions. It will be a dynamically calculated value – Hyz Jun 14 '21 at 17:24

1 Answers1

0

Does reative delata helps you?

from dateutil.relativedelta import relativedelta
    MyModel.objects.annotate(
        date_plus345=ExpressionWrapper(F('creation_date') + relativedelata(months+=40),
            output_field=DateTimeField()
        )
    )
lord stock
  • 1,191
  • 5
  • 32