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

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)