Search code examples
djangogoogle-app-enginesignalsdjangoappengine

Django, post_save signal recrusion. How to bypass signal firing


I have a situation where when one of my models is saved MyModel I want to check a field, and trigger the same change in any other Model with the same some_key.

The code works fine, but its recursively calling the signals. As a result I am wasting CPU/DB/API calls. I basically want to bypass the signals during the .save(). Any suggestions?

class MyModel(models.Model):
    #bah
    some_field = #
    some_key = #

#in package code __init__.py 
@receiver(models_.post_save_for, sender=MyModel)
def my_model_post_processing(sender, **kwargs):
 # do some unrelated logic...
 logic = 'fun!  '


 #if something has changed... update any other field with the same id
 cascade_update = MyModel.exclude(id=sender.id).filter(some_key=sender.some_key)
 for c in cascade_update:
     c.some_field  = sender.some_field 
     c.save()

Solution

  • Disconnect the signal before calling save and then reconnect it afterwards:

    post_save.disconnect(my_receiver_function, sender=MyModel)
    instance.save()
    post_save.connect(my_receiver_function, sender=MyModel)