Django: timezone.now vs timezone.now()

In python everything is an object, including functions. This means you can affect a function to a variable:

>>> from django.utils import timezone
>>> foo = timezone.now
>>> foo
<function django.utils.timezone.now>
>>> foo()
datetime.datetime(2016, 7, 7, 9, 11, 6, 489063)

A function is a callable object:

>>> callable(foo)
True
>>> callable(foo())
False

When default receives a callable, the callable is called each time a default value is requested.

On the other hand, when you call timezone.now() prior to setting default, the value is given and fixed. As a reminder, the following line is executed only once at server start up, since it is a class attribute:

    datetime_released = models.DateTimeField(default=timezone.now())

and thus timezone.now() is executed only once. Passing a callable timezone.now makes it possible to recalculate the value whenever it needs to be.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)