仅在事务完成后触发 post_save 信号 [英] Trigering post_save signal only after transaction has completed
问题描述
我已经编写了一些 API,它们各自的功能在事务块中执行.我在一个/几个模型/s的实例/s上调用save()
方法(经过一些修改),并在Elasticsearch中连续索引实例/s的一些JSON相关信息.我希望数据库回滚,即使出于某种原因,其中一个实例的 save()
或索引到 Elasticsearch 失败.
I have written some APIs, for which the respective functions executive inside a transaction block. I am calling the save()
method (after some modifications) on instance/s of a/several Model/s, and also consecutively indexing some JSON related information of the instance/s in Elasticsearch. I want the database to rollback even if for some reason the save()
for one of the instances or indexing to the Elasticsearch fails.
现在,问题出现了,即使在事务块内部,post_save()
信号也会被调用,这是一个问题,因为一些通知正在从这些信号中触发.
Now, the problem is arising that even inside the transaction block, the post_save()
signals gets called, and that is an issue because some notifications are being triggered from those signals.
有没有办法在交易成功完成后触发 post_save()
信号?
Is there a way to trigger post_save()
signals only after the transactions have completed successful?
推荐答案
并非如此.这些信号与 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.
这篇关于仅在事务完成后触发 post_save 信号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!