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.

oja
  • 41
  • 1
  • 2

3 Answers3

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)
awwester
  • 9,623
  • 13
  • 45
  • 72
  • What error do you get? Does the signal not run? Does it not call the model method properly? Have you seen posts such as http://stackoverflow.com/questions/13014411/django-post-save-signal-implementation – awwester May 30 '15 at 11:03
  • 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 – Eli O. Jun 27 '19 at 14:24
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

Community
  • 1
  • 1
Ahmed
  • 2,825
  • 1
  • 25
  • 39
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
Saman
  • 29
  • 1
  • 8