Django Signals How to find if it's an insert or update in the pre_save signal

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

By utilizing the pre_save we can determine if a save action on our database was about updating an existing object or creating a new one.

In order to achieve this you can check the state of the model object:

    @receiver(pre_save, sender=User)
    def pre_save_user(sender, instance, **kwargs): 
        if not instance._state.adding:
            print ('this is an update')
        else:
            print ('this is an insert')

Now every time a save action takes place, the pre_save signal will run and will print:

  • this is an update if the action derived from an update action.
  • this is an insert if the action derived from an insert action.

Note that this method does not require any additional database queries.



Got any Django Question?