Skip to content

Instantly share code, notes, and snippets.

@bakayim
Last active September 2, 2018 21:24
Show Gist options
  • Save bakayim/551f91d2bc1e741f47d965c5c7703fc6 to your computer and use it in GitHub Desktop.
Save bakayim/551f91d2bc1e741f47d965c5c7703fc6 to your computer and use it in GitHub Desktop.
Non-atomic Operation
# 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.
#############################################################################
# atomic is usable both as a decorator:
from django.db import transaction
@transaction.atomic
def viewfunc(request):
# This code executes inside a transaction.
do_stuff()
#############################################################################
# and as a context manager:
from django.db import transaction
def viewfunc(request):
# This code executes in autocommit mode (Django's default).
do_stuff()
with transaction.atomic():
# This code executes inside a transaction.
do_more_stuff()
#############################################################################
# Wrapping atomic in a try/except block allows for natural handling of integrity errors:
from django.db import IntegrityError, transaction
@transaction.atomic
def viewfunc(request):
create_parent()
try:
with transaction.atomic():
generate_relationships()
except IntegrityError:
handle_exception()
add_children()
#############################################################################
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment