Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use timedelta with timezone.now as default?

In Django models, How to increment the date field using timezone.now?

working:

end_date = models.DateTimeField(default=timezone.now() + timezone.timedelta(days=365))

Not Working

end_date = models.DateTimeField(default=timezone.now + timezone.timedelta(days=365))

I think timezone.now is a function which runs every time when the object is created. so that error occurs.

like image 836
rajagopalx Avatar asked Mar 08 '23 18:03

rajagopalx


1 Answers

You could use a function:

def f():
   return timezone.now() + timezone.timedelta(days=365)
...
end_date = models.DateTimeField(default=f)

The current time in that timezone is the added with the timedelta anytime a new end_date is created by default:

>>> from django.utils import timezone
>>> from datetime import timedelta
>>> def f():
...    return timezone.now() + timezone.timedelta(days=365)
... 
>>> f()
datetime.datetime(2018, 6, 25, 19, 42, 49, 761389, tzinfo=<UTC>)
>>> f()
datetime.datetime(2018, 6, 25, 19, 43, 2, 953158, tzinfo=<UTC>)

Sample run with Django:

In [1]: from testapp import models

In [2]: models.Test.objects.create().date_added
Out[2]: datetime.datetime(2018, 6, 25, 20, 5, 28, 316214, tzinfo=<UTC>)

In [3]: models.Test.objects.create().date_added
Out[3]: datetime.datetime(2018, 6, 25, 20, 5, 33, 114624, tzinfo=<UTC>)
like image 65
Moses Koledoye Avatar answered Mar 11 '23 06:03

Moses Koledoye