python / intermediate
Snippet
Django atomic Transaction Management
The atomic context manager wraps database operations in a transaction, ensuring all changes commit together or none commit if an error occurs. This prevents partial updates that would corrupt data integrity. Using update_fields limits the SQL UPDATE to only changed columns, improving performance. The transaction automatically rolls back when an exception propagates outside the with block.
snippet.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
from django.db import transactionfrom decimal import Decimaldef transfer_funds(sender, receiver, amount):with transaction.atomic():sender.balance -= amountsender.save(update_fields=['balance'])receiver.balance += amountreceiver.save(update_fields=['balance'])TransactionLog.objects.create(from_account=sender,to_account=receiver,amount=amount)if sender.balance < 0:raise ValueError('Insufficient funds')def batch_import_products(products_data):try:with transaction.atomic():for data in products_data:Product.objects.create(**data)return Trueexcept Exception:return False
django
Breakdown
1
with transaction.atomic():
Creates a transaction block; all operations succeed or all fail together
2
sender.save(update_fields=['balance'])
Partial update only the balance field, avoiding timestamp changes
3
raise ValueError('Insufficient funds')
Uncaught exception causes automatic rollback of all changes
4
except Exception:
Catches rollback exception; data remains consistent