Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
723 views
in Technique[技术] by (71.8m points)

python - Django default=timezone.now() saves records using "old" time

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...