I have a column type DateTimeField
with auto_now_add
, that seems to act as expected when creating a new record. However, when “updating” that record the field is set to Null
.
Now, I may be updating in a slightly peculiar manner, in that I know the id
of the record, and I do not care whether that id exists or not – Django figures out whether it is an insert
or an update
when I use .save()
.
from my_project.models import MyModel
mymodel = MyModel()
mymodel.id = '1'
mymodel.save()
#createdate field is set correctly
yourmodel = MyModel()
yourmodel.id = '1'
yourmodel.save()
#createdate is set to Null
#save mymodel again, without any changes
mymodel.save()
#createdate field is set correctly
I checked the connection.queries
and the documentation, and what Django seems to do is: if there is a primary key in the object upon .save()
being called it attempts an update
, if the update fails it will use insert
.
The connection.queries
reveal that:
When a new model object is created it has a createdate
value of None
, after object.save()
the createdate
is updated to an expected value. But, at the initial update
attempt by Django the createdate
is Null
in the sql, then on the insert
it is set to an appropriate value.
Where there is no existing record with the primary key, then the insert
is what modifies the database. However, when there is a record with the primary key, the update
is successful, and Django appears to expect the createdate
to have been populated prior to the .save()
.
Due to the special type of field, timestamp with a creation date, I wouldn’t expect the field to be updated, and for Django to understand/respect that.
The alternative is that I manually add the createdate to the database, and let MySQL manage the timestamp - but I think I am then going to have trouble retrieving that in Django.
I don’t really want to have to check for the existence of the primary key first, so, is there a way around this, and what’s the verdict on whether this is a bug, or a feature?