Django DateTimeField auto_now_add 不起作用
在其中一个模型中,我设置了一个时间戳字段,如下所示:
created_datetime = models.DateTimeField(auto_now_add = True)
在 shell 中,我可以创建一个 obj 并保存它,但是在我的应用程序中,它引发了一个异常,created_datetime 字段不能为空。
很困惑哪里出了问题!!如何重新爱它。
In one of the model i have set one timestamp field as follows:
created_datetime = models.DateTimeField(auto_now_add = True)
While in shell i am able to create a obj and save it, however in my application it is raising a exception that created_datetime field cannot be null.
Confused where things went wrong!! How to reslove it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
据我所知,默认日期时间的最佳实践是使用以下内容:
不要忘记导入日期时间
As far as I know, best practice for default datetimes is to use the following:
Don't forget to import datetime
我有这个,它真的让我困惑了很长时间。
事实证明,我的模型有一个自定义主键,这是由于在构造一些测试对象时未设置它的错误所致。
第一次,当
auto_now_add
设置created_at
时,效果很好。第二次没有,因为主键为空的对象已经存在,所以它正在进行更新。它尝试将其设置为created_at
null,这在我的模型中是不允许的。因此,值得检查一下您是否最终遇到此问题并出现错误“在我的应用程序中引发了一个异常,created_datetime 字段不能为空”,这可能是由于未正确设置主键造成的。
解决方案是我正确设置主键。
I had this and it really confused me for ages.
Turned out that my model had a custom primary key, and it was due to a bug not setting it when constructing some test objects.
The first time this worked fine as
auto_now_add
setcreated_at
. The second time it didn't as the object with a null primary key already existed, so it was doing an update. And it tried to set that tocreated_at
null, which wasn't allowed in my model.So worth checking if you end up on this question with the error "in my application it is raising a exception that created_datetime field cannot be null", that that could be caused by not setting a primary key correctly.
The solution was for me to correctly set a primary key.
你可以做这样的事情
You can do something like this
这意味着从数据库中调用旧保存的created_at数据,并在
更新
期间再次重新保存created_at 字段不起作用,因此静态保存,无需动态保存。
我的模型是
created_at = models.DateTimeField(auto_now_add=True)
It means call your old saved created_at data from database and re-save again during
Updation
created_at fields not working so save it statically, no need to do dynamically.
My model is
created_at = models.DateTimeField(auto_now_add=True)
以下方式位于django文档的“part1”中
The following way is in the "part1" of django documentation