How to stop recursion on Django's post_save signal

来源:互联网 发布:游族网络新游戏 编辑:程序博客网 时间:2024/06/06 19:01

In Django there's a signal called post_save which gets called after a model's save() method has been called. But what happens when you needed to update the instance inside the post_save like this:

1def do_stuff(sender, **kwargs):
2    kwargs['instance'].save()
3post_save.connect(do_stuff, sender=User)

This will fire another post_save signal that makes a recursion and local server stops. This can be solved by overriding the save() method instead and do processing there but I haven't seen a code where they override the user, instead they create profiles which isn't really what I need.

To solve the problem, you have to disconnect the signal before calling the save() method again while inside the post_save function and connect it again once its done.

1def do_stuff(sender, **kwargs):
2    post_save.disconnect(do_stuff, sender=User)
3    kwargs['instance'].save()
4    post_save.connect(do_stuff, sender=User)
5post_save.connect(do_stuff, sender=User)

This way when the save() method is called, it never fires another post_save signal because we've disconnected it.