Skip to content

Commit

Permalink
new tip
Browse files Browse the repository at this point in the history
  • Loading branch information
pybob committed Dec 13, 2023
1 parent 36cd1c3 commit c8a0e0c
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
1 change: 1 addition & 0 deletions index.md
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,7 @@ This file gets generated by [this script](index.py).

## Django

- [Automic database transactions](notes/20231213075301.md)
- [Django form save commit kwarg](notes/20221205115023.md)

## Dundermethods
Expand Down
46 changes: 46 additions & 0 deletions notes/20231213075301.md
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

0 comments on commit c8a0e0c

Please sign in to comment.