We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
它是这样工作的:当有请求过来时,Django会在调用视图方法前开启一个事务。如果请求却正确处理并正确返回了结果,Django就会提交该事务。否则,Django会回滚该事务。 with transaction.atomic(): 下面的代码支持事务
下面是被当做上下文管理器来使用:
from django.db import transaction
def viewfunc(request): # This code executes in autocommit mode (Django's default). do_stuff()
with transaction.atomic(): # This code executes inside a transaction. do_more_stuff()
一旦把atomic代码块放到try/except中,完整性错误就会被自然的处理掉了,比如下面这个例子:
from django.db import IntegrityError, transaction
@transaction.atomic def viewfunc(request): create_parent()
try: with transaction.atomic(): generate_relationships() except IntegrityError: handle_exception() add_children()
这个例子中,即使generate_relationships()中的代码打破了数据完整性约束,你仍然可以在add_children()中执行数据库操作,并且create_parent()产生的更改也有效。需要注意的是,在调用handle_exception()之前,generate_relationships()中的修改就已经被安全的回滚了。因此,如果有需要,你照样可以在异常处理函数中操作数据库。
The text was updated successfully, but these errors were encountered:
No branches or pull requests
它是这样工作的:当有请求过来时,Django会在调用视图方法前开启一个事务。如果请求却正确处理并正确返回了结果,Django就会提交该事务。否则,Django会回滚该事务。
with transaction.atomic():
下面的代码支持事务
下面是被当做上下文管理器来使用:
from django.db import transaction
def viewfunc(request):
# This code executes in autocommit mode (Django's default).
do_stuff()
一旦把atomic代码块放到try/except中,完整性错误就会被自然的处理掉了,比如下面这个例子:
from django.db import IntegrityError, transaction
@transaction.atomic
def viewfunc(request):
create_parent()
这个例子中,即使generate_relationships()中的代码打破了数据完整性约束,你仍然可以在add_children()中执行数据库操作,并且create_parent()产生的更改也有效。需要注意的是,在调用handle_exception()之前,generate_relationships()中的修改就已经被安全的回滚了。因此,如果有需要,你照样可以在异常处理函数中操作数据库。
The text was updated successfully, but these errors were encountered: