如何使用Django进行手动提交 [英] How to do to a manual commit using Django

查看:42
本文介绍了如何使用Django进行手动提交的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想执行一个事务以删除一些值,然后在db中计数,如果结果是<1,回滚时,我尝试了以下代码:

I would like to execute a transaction to delete some values, after that, count in db and if the result is < 1, rollback, i tried the following code:

@login_required
@csrf_exempt
@transaction.atomic
def update_user_groups(request):
    if request.POST:
        userId = request.POST['userId']
        groups = request.POST.getlist('groups[]')
        result = None
        with transaction.atomic():
            try:
                GroupsUsers.objects.filter(user_id=int(userId)).delete()
                for group in groups:
                    group_user = GroupsUsers()
                    group_user.user_id = userId
                    group_user.group_id = group
                    group_user.save()
                count = UsersInAdmin.objects.all().count()
                if count < 1:
                    transaction.commit()
                else:
                    transaction.rollback()
            except Exception, e:
                result = e
    return JsonResponse(result, safe=False)

谢谢

推荐答案

不可能在原子块内手动提交或回滚事务.

It's not possible to manually commit or rollback the transaction inside an atomic block.

相反,您可以在atomic块内部引发异常.如果该块完成,则将提交事务.如果引发异常,则事务将回滚.在原子块之外,您可以捕获异常并继续查看.

Instead, you can raise an exception inside the atomic block. If the block completes, the transaction will be committed. If you raise an exception, the transaction will be rolled back. Outside the atomic block, you can catch the exception and carry on your view.

try:
    with transaction.atomic():
        do_stuff()
        if ok_to_commit():
            pass
        else:
            raise ValueError()
except ValueError:
    pass

这篇关于如何使用Django进行手动提交的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆