Django transactions requests fail but still partially commit

丶灬走出姿态 提交于 2019-12-11 02:37:52

问题


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.

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.

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

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?

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


回答1:


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/



来源:https://stackoverflow.com/questions/8196404/django-transactions-requests-fail-but-still-partially-commit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!