Closed starryrbs closed 3 years ago
I don't think Django have a field for TIMESTAMP, you could use DateTimeField
with auto_now_add
.
class myModel(models.Model):
timestamp = models.DateTimeField(auto_now_add=True)
Thank you very much for your reply^_^.
If I use DateTimeField
with auto_now_add
, the database throws an exception of "Cannot insert an explicit value into a timestamp column" because Django's auto_now_add
is a value generated internally by Django.
I want to ask if there are any good solutions or is there a problem with my use?
It seems TIMESTAMP is deprecated and used to be an autogenerated value. This is now known as rowversion. Check here
Try and see if this works:
class myModel(models.Model):
timestamp = models.DateTimeField()
If you want to initialize with default server time, change data type of column to datetime2 and then you can try the above code from @absci or this:
from datetime import datetime
class myModel(models.Model):
timestamp = models.DateTimeField(default=datetime.now)
Thank you very much for your reply. @linkwithkk.
Using the default
cannot solve my problem, because the rowversion
field cannot be changed and inserted. The default
is still a value generated by python, and I expect the value generated by the database. I feel that this is a design problem of Django. I rewrote the save method of the model to solve this problem, but it is not a good solution.
I did not find a mapping for the TIMESTAMP field.