【发布时间】:2018-06-12 14:18:30
【问题描述】:
我想在 transaction.atomic() 块中对我的数据库执行操作,即使在引发错误的情况下也是如此。这是一些示例代码来演示我的问题:
示例代码
# Outer try block
try:
# Enclose in atomic transaction for database rollbacks
with transaction.atomic():
# If this line fails, all database updates within the outer try: block should be rolled back
u = UU.create(email='test@test.com')
# Inner try block
try:
cc = CC.objects.get(id=1)
perform_action(cc)
# If this exception triggers, the 'cc' object should be deleted, but all other database updates within the outer try: block should be rolled back
except:
cc.delete()
raise
# If this line fails, all database updates within the outer try: block should be rolled back
u = UU.create(email='test@test.com')
# If any exception triggers, this error should be printed
except:
print("Error occured.")
如果我的内部try: 块中发生错误,我希望删除cc 对象,但要回滚外部try: 块中的所有其他数据库事务。但是,就目前的代码而言,如果内部 try: 块内发生任何错误,cc.delete() 事务将被回滚。
有什么建议吗?
【问题讨论】:
标签: django exception transactions atomic