Django transactions requests fail but still partia

2019-07-11 14:03发布

问题:

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/