[Fixed]-Correct way of transaction.rollback() with raise exception in django

26👍

In this case – remove decorator, you can wrap part of code in your view:

try:
    with transaction.atomic():
        # ...
        if mal != '':
            raise IntegrityError

except IntegrityError:
    handle_exception()

Any operations attempted inside atomic will already have been rolled back safely when handle_exception() is called.

https://docs.djangoproject.com/en/dev/topics/db/transactions/#django.db.transaction.atomic

6👍

I have configured my db to 'ATOMIC_REQUESTS', so each request is also nested in a transaction.

I was looking for a way to rollback without raising an exception. I know, that’s not the original question, but for the record the following worked (django 1.11):

from django.db import transaction

def my_view(request):
    # some db interactions
    if it_hit_the_fan:
        transaction.set_rollback(True)
    # return response

Leave a comment