阅读此文档:https://docs.djangoproject.com/en/4.0/topics/db/transactions/#django.db.transaction.on_commit
on_commit
的使用场景。
with transaction.atomic(): # Outer atomic, start a new transaction
transaction.on_commit(foo)
# Do things...
with transaction.atomic(): # Inner atomic block, create a savepoint
transaction.on_commit(bar)
# Do more things...
# foo() and then bar() will be called when leaving the outermost block
但是为什么不直接写常规代码而不使用 on_commit
钩子呢?像这样:
with transaction.atomic(): # Outer atomic, start a new transaction
# Do things...
with transaction.atomic(): # Inner atomic block, create a savepoint
# Do more things...
foo()
bar()
# foo() and then bar() will be called when leaving the outermost block
这篇文章更容易阅读,因为不需要太多的Django应用程序编程接口的知识,语句以它们被执行的顺序排列。对于测试也更容易,因为您不必使用任何特殊的Django测试类。
那么on_commit
钩子的用例是什么呢?