How do you detect a new instance of the model in Django's model.save() [duplicate]
While overriding the specific model's save() method, Is it possible determine whether it's a new record or an update?
If self.pk
is None
it is a new record.
def save(self):
if self.pk is None:
self.created = datetime.today()
self.modified = datetime.today()
super(ProjectCost, self).save()
This topic has been discussed also here
The preferred solution in modern Django is to check self._state.adding
Unfortunately this is not currently documented, but there is an open task to do so https://code.djangoproject.com/ticket/31502
精彩评论