1

Without using signals, within the model save method is it possible to check whether a model is being created created or update? If so how?

def save(self, force_insert=False, force_update=False, *args, **kwargs): """ Override of save() method which is executed the same time the ``pre_save``-signal would be """ models.Model.save(self, *args, **kwargs) 
1
  • 5
    If it has a self.id, it's an update. Otherwise it's a new object. Commented Feb 13, 2014 at 13:33

3 Answers 3

4

You can check whether primary key has been created (i.e. is not None):

def save(self, force_insert=False, force_update=False, *args, **kwargs): if self.pk is None: # model is going to be created else: # model will be updated super(YourModelClass, self).save(*args, **kwargs) 

Note: when you check only if id: it would be treated as False in case when the id had value 0. Check this out:

>>> id = 0 >>> if id: ... print("ID is set to %s" % id) ... # no result, but the value is set! >>> id = 1 >>> if id: ... print("ID is set to %s" % id) ... ID is set to 1 >>> id = 0 >>> if id is not None: ... print("ID is set to %s" % id) ... ID is set to 0 
Sign up to request clarification or add additional context in comments.

Comments

1

Try like this,

def save(self, force_insert=False, force_update=False, *args, **kwargs): if self.id: # updated else: # inserted models.Model.save(self, *args, **kwargs) 

Comments

1

Another way to do this according to the Django documentation:

def save(self, force_insert=False, force_update=False, *args, **kwargs): is_create = self._state.adding if is_create: # Do create stuff else: # Do update stuff super().save(*args, **kwargs) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.