[Django]-Django: datetime.now() time inconsistency in model object save

5👍

auto_now_add is not a good approach. Avoid to use it. The best way is to use set default value:

from django.utils import timezone

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

django.utils.timezone will store the datetime according to your timezone settings.

Notice the missing () after timezone.now that is because we are passing a callable to the model and it will be called each time a new instance is saved. With the parentheses, it’s only being called once when models.py loads. This question clarifies this issue in more details.

2👍

You should not initialize the datetime.now() while defining the model. This causes some kind of “caching” the datetime.now.

Instead of:

Notification(from_user=from_user, to_user=to_user,
                            created_date=datetime.now())

You should use:

Notification(from_user=from_user, to_user=to_user,
                            created_date=datetime.now)

1👍

I believe it’s due to the way Pythons runtime environment processes, hopefully someone can re-iterate on that.
auto_add_now=True should be the solution as you’ve suggested.

Leave a comment