How to stop recursion on Django's post_save signal

本文介绍了如何在Django中使用post_save信号更新实例时避免无限递归的问题。通过在信号处理函数内部先断开信号连接,执行保存操作后再重新连接信号,可以有效地解决这一问题。

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:

1 def do_stuff(sender, **kwargs):
2     kwargs['instance'].save()
3 post_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.

1 def do_stuff(sender, **kwargs):
2     post_save.disconnect(do_stuff, sender=User)
3     kwargs['instance'].save()
4     post_save.connect(do_stuff, sender=User)
5 post_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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值