Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

django

I'm using Django's command to perform some tasks involving database manipulation:

class SomeCommand(BaseCommand):
    @transaction.atomic
    def handle(self, *args, **options):
        # Some stuff on the database

If an exception is thrown during execution of my program, @transaction.atomic guarantees rollback. Can I force this behavior without throwing exception? Something like:

# Doing some stuff, changing objects

if some_condition:
    # ABANDON ALL CHANGES AND RETURN
like image 392
Siegmeyer Avatar asked Sep 05 '16 13:09

Siegmeyer


People also ask

How do I rollback a Django transaction?

Once you're in a transaction, you can choose either to apply the changes you've performed until this point with commit() , or to cancel them with rollback() . These functions are defined in django. db. transaction .

Can't execute queries until the end of the atomic block?

You can't execute queries until the end of the 'atomic' block." is raised when you try to used a database connection after a database exception even those autocommit was set to false from the start. It should be up to the user how to handle the database exception and the transaction as autocommit was set to false.

How does Django handle concurrency?

In terms of Django, optimistic concurrency control can be implemented by overriding the save method on your model class... And, of course, for either of these concurrency mechanisms to be robust, you have to consider transactional control.


1 Answers

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.

like image 177
Day Avatar answered Sep 22 '22 15:09

Day