Trigering post_save signal only after transaction has completed

前端 未结 3 730
旧巷少年郎
旧巷少年郎 2020-12-30 02:27

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

3条回答
  •  无人及你
    2020-12-30 03:04

    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.

    There are 2 approaches here:

    • 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.

    Makes sense?

    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.

提交回复
热议问题