我想编写一个通用函数来处理Django为多个模型发出的post_save信号。
models.py
Class FirstModel(models.Model):
pass
Class AnotherModel(models.Model):
pass
Class YetAnotherModel(models.Model):
pass
对于models.py中的某些模型( FirstModel , AnotherModel ),我需要编写一个函数,可以在保存后执行一些常见操作。
AFAIK,我可以编写两个处理函数来接收发出的信号并执行常见操作。
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
但是我有兴趣知道任何更好的解决方案,使其像配置一样。
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
提前致谢:)
答案 0 :(得分:0)
您可以使用post_save.connect()
代替@receiver(post_save...)
。
无论是
post_save.connect(model_post_save_handler, sender=FirstModel)
post_save.connect(model_post_save_handler, sender=SecondModel)
或
for model in MODELS_TO_BE_POST_SAVE_HANDLED:
post_save.connect(model_post_save_handler, sender=model)
另请查看signals documentation,值得一读。