[Django]-Django: How to rollback (@transaction.atomic) without raising exception?

51👍

transaction.set_rollback can do this.

class SomeCommand(BaseCommand):
    @transaction.atomic
    def handle(self, *args, **options):
        # Doing some stuff, changing objects
        if some_condition:
            # Return, rolling back transaction when atomic block exits
            transaction.set_rollback(True)
            return

Quoting from the docs:

Setting the rollback flag to True forces a rollback when exiting the innermost atomic block. This may be useful to trigger a rollback without raising an exception.

👤Day

-2👍

Just call transaction.rollback().

Calling transaction.rollback() rolls back the entire transaction. Any uncommitted database operations will be lost.

You can see example in the docs.

-3👍

You can manage the code execution to raise or not an exception:

try:
    if some_condition:
        with transaction.atomic():
            # Your logic here
except Exception, e:  # An example, use a explicit error
    # Show something friendly instead of a exception
👤Gocht

Leave a comment