Django default=timezone.now() saves records using “old” time

蓝咒 提交于 2019-11-28 02:36:52

问题


This issue has been occurring on and off for a few weeks now, and it's unlike any that has come up with my project.

Two of the models that are used have a timestamp field, which is by default set to timezone.now().

This is the sequence that raises error flags:


  • Model one is created at time 7:30 PM

  • Model two is created at time 10:00 PM, but in the MySQL database it's stored as 7:30 PM!

Every model that is created has its time stamp saved under 7:30 PM, not the actual time, until a certain duration passes. Then a new time is set and all the following models have that new time... Bizzare


Some extra details which may help in discovering the issue:

I have a bunch of methods that I use to strip my timezones of their tzinfo's and replace them with UTC.

This is because I'm doing a timezone.now() - creationTime calculation to create a: "model was posted this long ago" feature in the project. However, this really should not be the cause of the problem.

I don't think using datetime.datetime.now() will make any difference either.

Anyway, thanks for the help!


回答1:


Just ran into this last week for a field that had default=date.today(). If you remove the parentheses (in this case, try default=timezone.now) then you're 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.




回答2:


Just set the parameter auto_now_add like this.

timestamp = models.DateTimeField(auto_now_add=True)

Update:

Please don't use auto_now_add. It is not the recommended way, instead do this:

from django.utils import timezone

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


来源:https://stackoverflow.com/questions/13225890/django-default-timezone-now-saves-records-using-old-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!