FreezeJ' Blog

Django事务代码

2022-08-16

官方文档:https://docs.djangoproject.com/zh-hans/3.2/topics/db/transactions/

通过装饰器

from django.db import transaction

@transaction.atomic
def viewfunc(request):
    do_stuff()

通过上下文管理器

from django.db import transaction

def viewfunc(request):
    do_stuff()

    with transaction.atomic():
        do_more_stuff()

异常捕捉

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()

设置保存点与还原

from django.db import transaction

@transaction.atomic
def add_author_views(request):
    sid1 = transaction.savepoint()  # 保存点
    u = User(name='test')
    u.save()
    sid2 = transaction.savepoint()  # 保存点
    if True:
        transaction.savepoint_commit(sid2)  # 保存创建
    else:
        transaction.savepoint_rollback(sid1)  # 还原为未创建用户的状态

    transaction.clean_savepoints()  #清除保存点

transaction不需要在代码中手动commitrollback的。因为只有当一个transaction正常退出的时候,才会对数据库层面进行操作。除非我们手动调用transaction.committransaction.rollback

查询锁

select_for_update返回一个查询集,该查询集将锁定行直到事务结束,从而在受支持的数据库上生成 SELECT ... FOR UPDATE SQL语句。

from django.db import transaction

entries = Entry.objects.select_for_update().filter(author=request.user)
with transaction.atomic():
    for entry in entries:
        ...