Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a function in Django after saving a model

Context: I'm making a blog. This blog stores information on articles in a database via a Django model. I have a FileField in said model that takes an archive of all the assets that go with this file. I add articles through the admin site.

I want to call a function that unpacks this file immediately after the the object is saved to the model. Where would I write this function?

like image 626
Abhishek Kasireddy Avatar asked Mar 31 '17 16:03

Abhishek Kasireddy


People also ask

What does save () do in Django?

The save method is an inherited method from models. Model which is executed to save an instance into a particular Model. Whenever one tries to create an instance of a model either from admin interface or django shell, save() function is run.

Do I need to save after create Django?

Creating objects To create a new instance of a model, instantiate it like any other Python class: class Model (**kwargs) The keyword arguments are the names of the fields you've defined on your model. Note that instantiating a model in no way touches your database; for that, you need to save() .

Does Django save call clean?

save() calls the clean. This way the integrity is enforced both from forms and from other calling code, the command line, and tests. Without this, there is (AFAICT) no way to write a test that ensures that a model has a FK relation to a specifically chosen (not default) other model.


2 Answers

You can use signal dispatcher included in Django.

from django.db.models.signals import post_save
from django.dispatch import receiver

from myapp.models import Blog

@receiver(post_save, sender=Blog)
def my_handler(sender, **kwargs):
    print('post save callback')

See https://docs.djangoproject.com/en/stable/ref/signals/#post-save for more information.

like image 94
Kirill Cherepanov Avatar answered Oct 20 '22 18:10

Kirill Cherepanov


Maybe you can use post_save signal in your app/model:

https://docs.djangoproject.com/en/1.10/ref/signals/#post-save

like image 24
XaviP Avatar answered Oct 20 '22 19:10

XaviP