Django DateTimeField auto_now_add not working

血红的双手。 提交于 2020-01-12 03:18:47

问题


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.


回答1:


You can do something like this

created_datetime = models.DateTimeField(auto_now_add=True, auto_now=False)



回答2:


As far as I know, best practice for default datetimes is to use the following:

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

Don't forget to import datetime




回答3:


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 set created_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 to created_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.




回答4:


The following way is in the "part1" of django documentation

from django.utils import timezone
p = Poll(question="What's new?", pub_date=timezone.now())


来源:https://stackoverflow.com/questions/5899868/django-datetimefield-auto-now-add-not-working

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