Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 :)

like image 404
Jagadesh Babu T Avatar asked Oct 31 '22 02:10

Jagadesh Babu T


1 Answers

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.

like image 160
Ivan Anishchuk Avatar answered Nov 08 '22 10:11

Ivan Anishchuk