Consolidating multiple post_save signals with one receiver

后端 未结 4 915
旧时难觅i
旧时难觅i 2020-12-15 02:37

So I read the Django source code (post 1.5) that you can now register multiple multiple signals to a receiver function:

def receiver(signal, **kwargs):
    \         


        
4条回答
  •  执笔经年
    2020-12-15 03:17

    You can skip model_name and you will connect to all models post_save. Then you can filter if you are in right model in the handler:

    post_save.connect(foo)
    
    def foo(sender, **kwargs):
        if sender not in [FooModel, BarModel]:
            return
        ... actual code ...
    

    or you can filter based on field in model:

    def foo(sender, **kwargs):
        if not getattr(sender, 'process_by_foo', False):
            return
        ... actual code ...
    

提交回复
热议问题