Django: Run Multiple Update Queries Faster with Database transaction

(Comments)

Django’s default behaviour is to run autocommit mode. Each query is immediately committed to the database unless a transaction is active.

Django provides a single API to control database transactions. atomic allows us to create a block of code or a function within which the atomicity of the database is guaranteed. If the block of code is successfully completed, the changes are committed to the database. If there is an exception, the changes are rolled back. 

atomic can be either used as a decorator or as a context manager.

Here is an example for atomic as a decorator

from django.db import transaction 

@transaction.atomic
def foo():
do_more() # Multiple update queries executes inside a transaction

An example for atomic as a context manager

from django.db import transaction

def foo():
do_stuff() # This code executes in Django's default autocommit mode.

with transaction.atomic():
do_more() # Multiple update queries executes inside a transaction

atomic blocks can be nested. In this case, when an inner block completes successfully, its effects can still be rolled back if an exception is raised in the outer block at a later point.

Currently unrated