pythondjangodjango-models

Django how to check whether a model is being created created or update


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)

Solution

  • 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)