Django default = timezone.now()使用“旧”保存记录时间 [英] Django default=timezone.now() saves records using "old" time
问题描述
这个问题已经在几个星期内出现了,而且与我的项目没有任何关系。
使用的两个模型都有一个时间戳记字段,默认情况下设置为 timezone.now()
。
这是引发错误标志的顺序:
-
模型一是在下午7:30时创建
-
模型二是在下午10点建立的,但在
MySQL数据库中存储为7:30 PM!
创建的每个模型
的时间戳都保存在下午7:30,而不是实际时间,直到某个
持续时间过去。然后设置一个新的时间,所有以下模型
有新的时间... Bizzare
一些额外的细节可能有助于发现问题:
我有一些方法,我用来剥离我们的时区他们的 tzinfo
并将其替换为UTC。
这是因为我正在做一个 timezone.now() - creationTime
计算来创建一个:模型很久以前就发布了功能
在项目中。但是,这真的不应该是问题的原因。
我不认为使用 datetime.datetime.now()$无论如何,感谢您的帮助!
刚刚在上个星期遇到了一个有 default = date.today()
的字段。如果你删除括号(在这种情况下,尝试 default = timezone.now
)然后你传递一个可调用的模型,它将被调用每次一个新的实例被保存。使用括号,当 models.py
加载时,它只会被调用一次。
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!
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.
这篇关于Django default = timezone.now()使用“旧”保存记录时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!