Django default = datetime.now () in models always saves the same time after uwsgi reset

I have this code in my model:

added_time = models.DateTimeField(
    default=datetime.datetime.now()
)

After migrating and rebooting uwsgi, I get the first datetime in MariaDB now, and further on - exactly the same as after resetting uwsgi.

2015-04-19 16:01:46
2015-04-19 16:01:46
2015-04-19 16:01:46
2015-04-19 16:01:46

I fixed it by changing the code to:

added_time = models.DateTimeField(
    auto_now_add=True
)

Although I fixed the problem, I'm not quite sure why this behavior was even like that?

+4
source share
2 answers

default=datetime.datetime.now()evaluated during parsing / compilation of the model. After that, it does not change. To evaluate now()while adding / updating an object, you should use:

default=datetime.datetime.now, now . Django .

auto_now_add, , ( - , , auto_now_add , ).

, .

+15

datetime.datetime.now datetime.datetime.now() . , .

. Django .

Django, django.utils.timezone.now datetime.datetime.now.

+5

All Articles