Search code examples
pythondjangodjango-modelsdjango-signals

Moving from Django signals to save override: How to translate the "created" parameter of a Django post_save signal for a save method override


I have made some bad decisions earlier regarding how I handle post_save events on a Django model and I am currently looking into changing my approach.

Let's begin by making my example. Here is my model.

class MyModel(models.Model):
    #... all my model creation and logic are here
    
    def do_something(self):
        # Actually do something, for the sake of simplifying the example, just write pass
        pass

Now, what I am using is a receiver function like this one. It works, but for many reasons that are mine, I want to stop using signal in this case.

@receiver(post_save, sender=MyModel)
def foo(sender, instance, created, **kwargs):
    if created:
        instance.do_something()

I imagine I could override the MyModel.save method, something like this:

class MyModel(models.Model):
    #... 

    def save(self):
        super().save()
        if created: # It is this line that I need to figure how to do. 
            self.do_something()

By what should I replace the if created: of my receiver function if I want to override the save() method? Or do you have something else to recommend?

I would also be curious if it is the same thing for pre_save signals.


Solution

  • If i understand your question you can try checking if current model instance pk is available or not

    def save(self, *args, **kwargs):
            is_created = self.pk is None  # Check if the instance is being created
    
            super().save(*args, **kwargs)
    
            if is_created:
                self.do_something()