我正在使用Django的命令执行一些涉及数据库操作的任务:
class SomeCommand(BaseCommand):
@transaction.atomic
def handle(self, *args, **options):
# Some stuff on the database
如果在执行程序期间抛出异常,@transaction.atomic
保证回滚。我可以强制执行此行为而不抛出异常吗?类似的东西:
# Doing some stuff, changing objects
if some_condition:
# ABANDON ALL CHANGES AND RETURN
答案 0 :(得分:10)
transaction.set_rollback
可以做到这一点。
class SomeCommand(BaseCommand):
@transaction.atomic
def handle(self, *args, **options):
# Doing some stuff, changing objects
if some_condition:
# Return, rolling back transaction when atomic block exits
transaction.set_rollback(True)
return
引自the docs:
将退回标志设置为
True
会在退出最里面的原子块时强制回滚。这可能有助于在不引发异常的情况下触发回滚。
答案 1 :(得分:-2)
答案 2 :(得分:-3)
您可以管理代码执行以引发或不引发异常:
try:
if some_condition:
with transaction.atomic():
# Your logic here
except Exception, e: # An example, use a explicit error
# Show something friendly instead of a exception