4

I want to call a method after this object (in this example Question) is 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 instance data is the old one (same as before the save). So some_method(instance) gets the old instance. But I need the instance with the new data.

1
  • Did you ever find a solution? Commented Mar 22, 2016 at 20:51

3 Answers 3

3

The method you call from post_save signal should be outside of the Model. You can put the method inside the models.py or in another file such as signals.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)
Sign up to request clarification or add additional context in comments.

2 Comments

What error do you get? Does the signal not run? Does it not call the model method properly? Have you seen posts such as stackoverflow.com/questions/13014411/…
Note that you ll have to add "from django.db.models.signals import post_save" at the top of your file for this to work
1

You can override save method, and call what ever you want after the object gets saved

Here is a related link: Django. Override save for model

Comments

0

What you want is something called signals: https://docs.djangoproject.com/en/3.2/topics/signals/. Some operations send a signals before and after they're completed successfully. In the docs you can find a list of built-in signals. You can also create custom signals. For example assume that I want to do something specific each time a new user is created. Then my code would be something like this:

users/models.py

from django.contrib.auth.models import AbstractUser
from django.dispatch import receiver
from django.db.models.signals import post_save

class CustomUser(AbstractUser):
    pass

###############
# Recieve the signals and get the signals that are sent
# after models are saved and whose sender is CustomUser
###############
@receiver(post_save, sender='CustomUser')
def do_something():
    do_something_specific

You can also save your signals in a separate file called signals.py but you need to change your app's apps:

<appname>/apps.py

from django.apps import AppConfig

class AppnameConfig(AppConfig):
    name = <appname>

    def ready(self):
        import <appname>.signals

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.