Django call method after saving object with new instance

I want to call a method after this object (in this example Question

) has been saved. This is what I got:

class Question(models.Model):
    ...

    def after_save(sender, instance, *args, **kwargs):
        some_method(instance)

post_save.connect(Question.after_save, sender=Question)

      

It kind of works. But the problem is that the data instance

is old (the same as before saving). So, some_method(instance)

gets old instance

. But I need an instance with new data.

+3


source to share


2 answers


The method you call from the post_save signal must be outside the model. You can put this method in models.py or another file like signal.py



class Question(models.Model):
    ...
    def some_method(self):
        return "hello"

def question_saved(sender, instance, *args, **kwargs):
    instance.some_method()

post_save.connect(question_saved, sender=Question)

      

+2


source


You can override the save method and call whatever you want after saving the object



Here is the link: Django. Override save for model

+1


source







All Articles