Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - Difference between admin save_model() and post_save signal

For my application I need to do extra operations when a model is saved via form. In practice, I need to add a value in another model if certain conditions are present in the form.

To do this I have two options, but I want to understand the pros and cons of both.

  1. Use the post_save signal
  2. Overwrite the save_model method in admin.py, since it is said in the documentation that "Overriding this method allows doing pre- or post-save operations."

I currently use the latter in this way

def save_model(self, request, obj, form, change):

    #some pre save operations....

    #this call the save model method
    super(MyModelAdmin, self).save_model(request, obj, form, change)

    #some post save operations...

and it works

But what I want to understand is:

  1. For what I must do, what are the differences between the two approaches and what is the most correct.
  2. Is the save_model method related to the use of the admin interface? What happens if I use another frontend different from Django's admin?
  3. In general, what is the difference between doing pre and post save operations overwriting save_model and using signals?
like image 321
max Avatar asked Sep 15 '25 01:09

max


1 Answers

I think you got it right. And this might help you to understand the difference.

save_model method from ModelAdmin called when you are trying to create or update something from django admin only but signals are triggered regardless of place where actions happened. Which means pre or post operations in save_model method won't work if you change model from somewhere outside of django admin but signals will work for both from outside of admin views and from your custom written code blocks.

like image 158
Davit Tovmasyan Avatar answered Sep 17 '25 00:09

Davit Tovmasyan