Django - 回滚保存与事务原子 [英] Django - Rollback save with transaction atomic

查看:320
本文介绍了Django - 回滚保存与事务原子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个保存对象的视图,但是如果引发了一些异常,我希望保存 。这是我试过的:

  class MyView(View):

@ transation.atomic
def post(self,request,* args,** kwargs):
try:
some_object = SomeModel(...)
some_object.save()

如果有事情:
raise exception.NotAcceptable()
#当工作流进入这个条件时,我认为以前的保存应该是undome
#我错过了吗?

except exception.NotAcceptable,e:
#do something

我做错了什么?即使出现异常 some_object 仍然在DataBase中。

解决方案

原子性文档 @ transaction.atomic 将在数据库上执行事务。因为你自己捕获了这个例外,所以Django看来你的视图执行得很好。



如果你捕捉到异常,你需要自己处理:控制事务



如果您需要在发生故障时生成正确的json响应:

  from django.db导入SomeError,transaction 

def viewfunc(request):
do_something()

try:
with transaction.atomic():
thing_that_might_fail()
除了SomeError:
handle_exception()

render_response()


I am trying to create a view where I save an object but I'd like to undo that save if some exception is raised. This is what I tried:

class MyView(View):

    @transation.atomic
    def post(self, request, *args, **kwargs):
        try:
            some_object = SomeModel(...)
            some_object.save()

            if something:
                raise exception.NotAcceptable()
                # When the workflow comes into this condition, I think the previous save should be undome
                # Whant am I missing?

        except exception.NotAcceptable, e:
            # do something

What am I doing wrong? even when the exception is raised some_object is still in DataBase.

解决方案

Atomicity Documentation

To summarize, @transaction.atomic will execute a transaction on the database if your view produces a response without errors. Because you're catching the exception yourself, it appears to Django that your view executed just fine.

If you catch the exception, you need to handle it yourself: Controlling Transactions

If you need to produce a proper json response in the event of failure:

from django.db import SomeError, transaction

def viewfunc(request):
    do_something()

    try:
        with transaction.atomic():
            thing_that_might_fail()
    except SomeError:
        handle_exception()

    render_response()

这篇关于Django - 回滚保存与事务原子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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