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 :)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With