Skip to content

Latest commit

 

History

History
46 lines (32 loc) · 1.69 KB

20231213075301.md

File metadata and controls

46 lines (32 loc) · 1.69 KB

Automic database transactions

Ensure the integrity of your database transactions with transaction.atomic() which guarantees atomicity: all operations within the block either complete successfully or roll back if an error occurs.

Use it to group related operations (e.g. on multiple related models) into a single unit, ensuring either all succeed or none, maintaining data consistency.

from django.db import transaction

# 1. as context manager

def my_view(request):
    # Non-atomic operations...
    with transaction.atomic():
        # Atomic block starts
        # Database operations here
        # Atomic block ends


# 2. as decorator

@transaction.atomic
def my_view(request):
    # Entire view is an atomic block

Fascinating detail is this multi-use of the atomic object 😍, source:

# https://docs.djangoproject.com/en/4.1/_modules/django/db/transaction/

def atomic(using=None, savepoint=True, durable=False):
    # Bare decorator: @atomic -- although the first argument is called
    # `using`, it's actually the function being decorated.
    if callable(using):
        return Atomic(DEFAULT_DB_ALIAS, savepoint, durable)(using)
    # Decorator: @atomic(...) or context manager: with atomic(...): ...
    else:
        return Atomic(using, savepoint, durable)

The first if statement checks if the first argument (using) is a callable, which in Python typically is a function. If "using" is a function, it implies that atomic is being used as a decorator.

If atomic is not used as a decorator (meaning the "using" argument is not a callable function), it implies that it's being used as a context manager (so the enter and exit special methods of the Atomic class kick in).

#Django