Django事务请求失败但仍部分提交 [英] Django transactions requests fail but still partially commit

查看:148
本文介绍了Django事务请求失败但仍部分提交的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我提交表单时,我必须将两个对象保存到数据库中;但是,如果第一个和第二个保存之间出现故障,我仍然看到数据库中的第一个对象。

When I submit a form I have to save two objects to the database; however if there is a failure in between the first and second saves, I still see the first object in the database.

因为我在主要的设置中启用了TransactionMiddleware,想要(并期待)请求的失败,回滚我作为此请求的结果的任何数据库更新。

Because I have enabled TransactionMiddleware in the main settings, I wanted (and was expecting) the failure of the request to roll back any database update that I had made as a result of this request.

我的代码如下: / p>

My code is as follows:

def submit(request):
    form1 = Form1(request.POST)
    form2 = Form2(request.POST)

    obj1 = form1.save()

    # simulate an error
    raise Exception('spam', 'eggs')

    obj2 = form2.save(commit=False)
    obj2.obj1 = obj1
    form2.save() 

当我随后查询数据库时,存在obj1。作为失败的结果,如何让它回滚obj1事务?

When I subsequently query the database, obj1 is present. How do I get it to rollback the obj1 transaction as a result of the failure?

(我也尝试将装饰器@ transaction.commit_on_success,但是obj1仍然是存储在数据库中)

(I've also tried putting the decorator @transaction.commit_on_success, but obj1 is still stored in the database).

推荐答案

这一切都取决于您使用的数据库,对于MySQL,您需要使用表格来使用Innodb (直到最近不是默认的)。

It all depends on the database you are using, for MySQL you need your table to use Innodb (which until recently was not the default).

https:/ /docs.djangoproject.com/en/dev/topics/db/transactions/

这篇关于Django事务请求失败但仍部分提交的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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