Django DateTimeField auto_now_add not working

前端 未结 4 851
花落未央
花落未央 2021-02-04 08:04

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

4条回答
  •  耶瑟儿~
    2021-02-04 08:44

    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.

提交回复
热议问题