Django:在 transaction.atomic 的异常之后继续执行代码

Django: continuing code execution after transaction.atomic's Exception

可能这是一个非常愚蠢的问题,但我正在研究的部分非常重要,所以我想检查两次)

引用 Django documentation 关于 with transaction.atomic():

Atomicity is the defining property of database transactions. atomic allows us to create a block of code within which the atomicity on the database is guaranteed. If the block of code is successfully completed, the changes are committed to the database. If there is an exception, the changes are rolled back. My Guess: And the following code will not be executed, because a regular python Exception raised, right?

例如:

def my_view(request):

    with transaction.atomic():
        # bunch of queries

    api_call()

    return JsonResponse('Done')

如果transaction.atomic()块内发生数据库异常,是否保证不会执行api_call()?非常感谢

没错。这不是特定于 Django 的:数据库异常是一种 Exception,如果 Exception 在 Python 中引发(并且未被捕获),后续代码将不会被执行。