How to handle Django Singals emitted by multiple models using a common function

1.8k views Asked by At

I would like to write a common function to handle the post_save signal emitted by Django for multiple models.

models.py

Class FirstModel(models.Model):
    pass

Class AnotherModel(models.Model):
    pass

Class YetAnotherModel(models.Model):
    pass

For some models (FirstModel, AnotherModel) in my models.py I need to write a function which can do some common action post save.

AFAIK, I can write two handler functions to receive the emitted signals and do the common action.

signals.py

@receiver(post_save, sender=FirstModel)
def first_model_post_save_handler(sender, **kwargs):
    pass

@receiver(post_save, sender=AnotherModel)
def another_model_post_save_handler(sender, **kwargs):
    pass

However I am interested in knowing any better solution to make it like a configuration.

configuration.py

MODELS_TO_BE_POST_SAVE_HANDLED = ['FirstModel', 'AnotherModel']

singals.py

@receiver(post_save, sender=MODELS_TO_BE_POST_SAVE_HANDLED)
def first_model_post_save_handler(sender, **kwargs):
    pass

Thanks in advance :)

1

There are 1 answers

0
Ivan Anishchuk On

You can use post_save.connect() instead of @receiver(post_save...).

Either as

post_save.connect(model_post_save_handler, sender=FirstModel)
post_save.connect(model_post_save_handler, sender=SecondModel)

or as

for model in MODELS_TO_BE_POST_SAVE_HANDLED:
    post_save.connect(model_post_save_handler, sender=model)

Also take a look at the signals documentation, it's worth reading.