-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
47 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
# 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 |