将每个HTTP 请求封装在一个数据库事务中
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': '',
'USER': '',
'PASSWORD': '',
'HOST': '',
'PORT': '',
'ATOMIC_REQUESTS': True,
}
}
如果需要禁用Django 的事务管理并自己实现,设置它为False, 但不建议这样做。
无视全局事务设置,恢复Django默认的自动提交模式
单个方法事务控制
from django.db import transaction
@transaction.atomic
def viewfunc(request):
# This code executes inside a transaction.
do_stuff()
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()
设置保存点
from django.db import transaction
# open a transaction
@transaction.atomic
def viewfunc(request):
a.save()
# transaction now contains a.save()
sid = transaction.savepoint()
b.save()
# transaction now contains a.save() and b.save()
if want_to_keep_b:
# 释放保存点
transaction.savepoint_commit(sid)
# open transaction still contains a.save() and b.save()
else:
transaction.savepoint_rollback(sid)
# open transaction now contains only a.save()
如果b.save()
抛出异常,所有未提交操作都会回滚。
调用 transaction.rollback() 回滚整个事物。任何未提交的数据库操作都会丢失。在此例中, 由 a.save()所保存的变更将会丢失,即使这个操作自身没有产生错误。
a.save() # Succeeds, but may be undone by transaction rollback
try:
b.save() # Could throw exception
except IntegrityError:
transaction.rollback()
c.save() # Succeeds, but a.save() may have been undone
如果b.save()
抛出异常,a.save()
后的未提交操作都会被回滚
a.save() # Succeeds, and never undone by savepoint rollback
sid = transaction.savepoint()
try:
b.save() # Could throw exception
# 释放保存点
transaction.savepoint_commit(sid)
except IntegrityError:
transaction.savepoint_rollback(sid)
c.save() # Succeeds, and a.save() is never undone
transaction.savepoint()
之前的代码永不会被回滚