且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

仅在事务完成后触发 post_save 信号

更新时间:2023-11-21 09:46:28

并非如此.这些信号与 db 事务的成功或失败无关,而是与 save 方法本身有关 - 在调用之前你有 pre_save 信号被触发,在调用之后你有 post_save 信号被触发.

Not really. The signals have nothing to do with the db transaction success or failure, but with the save method itself - before the call you have the pre_save signal fired and after the call you have the post_save signal fired.

这里有两种方法:

  • 您将检查 post_save 方法中的实例并决定模型是否成功保存;最简单的方法:在 save 方法中,在事务成功执行后,用一个标志注释你的实例,比如 instance.saved_successfully = True,你将在 post_save 处理程序中测试.
  • 您将放弃 post_save 信号并为自己创建一个自定义信号,您将在交易成功运行后触发该信号.
  • you are going to inspect the instance in the post_save method and decide that the model was saved successfully or not; simplest way to do that: in the save method, after the transaction executed successfully, annotate your instance with a flag, say instance.saved_successfully = True, which you will test in the post_save handler.
  • you are going to ditch the post_save signal and create a custom signal for yourself, which you will trigger after the transaction ran successfully.

有意义吗?

附言

如果您确实需要绑定到事务提交信号,请查看此包:https://django-transaction-hooks.readthedocs.org/en/latest/;看起来该功能已集成在 Django 1.9a 中.

If you strictly need to bind to the transaction commit signal, have a look over this package: https://django-transaction-hooks.readthedocs.org/en/latest/; it looks like the functionality is integrated in Django 1.9a.