Search code examples
pythondjangodjango-modelsdjango-signals

Django: Is there a way to cancel an receiver triggering for a particular model signal?


I have a post_save signal receiver for a model in my domain. This receiver is triggered by many routines that run a save on that model (therefore I can't delete that receiver yet).

@receiver(signal=post_save, sender=OrderGroup)
def check_commission_should_be_synced(sender, instance, created, **kwargs):
    # Receiver procedure
    # ...

I would like to cancel its triggering for a particular method that manipulates my model. Is that possible?

I'm using Django 1.7 with Python 2.7.


Solution

  • Add a non-database Boolean attribute to your model defaulting to False, like:

    class MyModel(models.Model):
        # existing datanase fields
        trigger_post_save = False
    

    and for the methods you don't want to trigger post_save, set it to True before save:

    my_instance.trigger_post_save = True
    my_instance.save()
    

    Finally, in your decorated method check the value and return if it's set:

    @receiver(signal=post_save, sender=OrderGroup)
    def check_commission_should_be_synced(sender, instance, created, **kwargs):
        if instance.trigger_post_save:
            return
        # the rest of code