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
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 .
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With