django action when create model 1

django action when create model

# override create model method (django)

class MyModel(models.Model):
  name = ....
  ........
  .......
  def save(self, *args, **kwargs):
      if not self.pk:
          # This code only happens if the objects is
          # not in the database yet. Otherwise it would
          # have pk
          
          # -- do your custom actions here --
          
      super(MyModel, self).save(*args, **kwargs) # activate the default method on update

Here is what the above code is Doing:
1. The save() method is called when you create a new object and when you update an existing object.
2. The first line checks if the object has a primary key assigned to it. If it does, it means that the object is already in the database.
3. If the object is not in the database yet, the code inside the if statement will be executed.
4. The last line calls the default save() method. This is important because it saves the object to the database.

Similar Posts