[Django]-How do you detect a new instance of the model in Django's model.save()

58👍

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

9👍

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

Leave a comment