仅在交易完成后才触发post_save信号 [英] Trigering post_save signal only after transaction has completed
问题描述
我已经编写了一些API,它们的相应功能在事务块内执行.我正在对一个或多个Model/s的实例调用save()
方法(经过一些修改),并且还在 Elasticsearch 中连续索引该实例的一些与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.
这里有2种方法:
- 您将使用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.
有道理吗?
P.S.
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屋!