Django post_save防止递归而不覆盖模型save() [英] Django post_save preventing recursion without overriding model save()

查看:98
本文介绍了Django post_save防止递归而不覆盖模型save()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有很多Stack Overflow帖子关于使用 post_save 信号的递归,评论和答案绝对是:为什么不覆盖save()或保存只有在 created == True 才被触发。

There are many Stack Overflow posts about recursion using the post_save signal, to which the comments and answers are overwhelmingly: "why not override save()" or a save that is only fired upon created == True.

我相信没有使用 save() - 例如,我正在添加一个临时应用程序,处理订单履行数据完全独立于我们的订单模型。

Well I believe there's a good case for not using save() - for example, I am adding a temporary application that handles order fulfillment data completely separate from our Order model.

框架的其余部分幸福地不知道履行应用程序,并使用post_save钩子将所有履行相关的代码从我们的订单模型中分离出来。

The rest of the framework is blissfully unaware of the fulfillment application and using post_save hooks isolates all fulfillment related code from our Order model.

如果我们删除履行服务,我们的核心代码必须改变。我们删除了履行应用程序,就是这样。

If we drop the fulfillment service, nothing about our core code has to change. We delete the fulfillment app, and that's it.

所以,有没有什么正确的方法来确保post_save信号不会触发相同的处理程序两次?

So, are there any decent methods to ensure the post_save signal doesn't fire the same handler twice?

推荐答案

如何断开连接,然后重新连接 post_save 函数中的信号:

How about disconnecting then reconnecting the signal within your post_save function:

def my_post_save_handler(sender, instance, **kwargs):
    post_save.disconnect(my_post_save_handler, sender=sender)
    instance.do_stuff()
    instance.save()
    post_save.connect(my_post_save_handler, sender=sender)
post_save.connect(my_post_save_handler, sender=Order)

这篇关于Django post_save防止递归而不覆盖模型save()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆