How does Django handle database transactions and atomic operations?
How Django handles transactions with transaction.atomic(): autocommit, rollbacks, savepoints, and select_for_update for safe concurrent writes.
Expected Interview Answer
Django manages transactions through django.db.transaction, most commonly with transaction.atomic() used as a decorator or context manager, which wraps a block of code so all its database writes either commit together or roll back entirely on any exception.
By default Django runs in autocommit mode, committing each query immediately. Wrapping code in atomic() opens a transaction (or a savepoint if nested) and commits it only when the block exits cleanly; any raised exception triggers a rollback to keep data consistent. You can also enable ATOMIC_REQUESTS to wrap every view in a transaction, and use select_for_update() to lock rows against concurrent modification. Nested atomic() blocks use savepoints so an inner failure can roll back without discarding the whole outer transaction.
- Guarantees all-or-nothing writes for related operations
- Prevents partial updates that leave data inconsistent
- Supports nested blocks via savepoints
- Enables row locking with select_for_update to avoid race conditions
- Can wrap entire requests via ATOMIC_REQUESTS
AI Mentor Explanation
An atomic transaction is like a completed over in cricket: either all six legal deliveries are bowled and recorded, or if the over is abandoned mid-way the partial deliveries do not count as a finished over. Django's atomic() commits every write together, and one failed ball — an exception — rolls the whole block back as if it never started.
Step-by-Step Explanation
Step 1
Understand autocommit
By default each query commits immediately, so unrelated writes are independent unless grouped.
Step 2
Wrap in atomic()
Use transaction.atomic() as a decorator or with-block to group writes into one commit-or-rollback unit.
Step 3
Let exceptions roll back
Any exception escaping the atomic block triggers an automatic rollback of all its writes.
Step 4
Nest with savepoints
Inner atomic() blocks create savepoints so an inner failure rolls back only that portion.
Step 5
Lock rows when needed
Use select_for_update() inside atomic() to lock rows and prevent concurrent modification.
What Interviewer Expects
- Knowing atomic() is the primary transaction API
- Explaining autocommit as the default mode
- Understanding rollback on exception
- Awareness of nested atomic and savepoints
- Mentioning select_for_update or ATOMIC_REQUESTS
Common Mistakes
- Catching an exception inside atomic() and continuing, corrupting the transaction state
- Assuming each query is transactional without wrapping related writes
- Confusing ATOMIC_REQUESTS with per-view atomic control
- Using select_for_update outside an atomic block where it has no effect
- Doing slow external calls like emails inside a long-held transaction
Best Answer (HR Friendly)
“Django groups related database changes so they all succeed or all fail together, using a tool called atomic(). This is like a bank transfer where money must move fully or not at all, which keeps the data from ending up half-updated if something goes wrong.”
Code Example
from django.db import transaction
from .models import Account
@transaction.atomic
def transfer(from_id, to_id, amount):
sender = Account.objects.select_for_update().get(pk=from_id)
receiver = Account.objects.select_for_update().get(pk=to_id)
if sender.balance < amount:
raise ValueError('Insufficient funds') # rolls back everything
sender.balance -= amount
receiver.balance += amount
sender.save()
receiver.save()Follow-up Questions
- What is the difference between autocommit and atomic mode?
- How do nested atomic() blocks and savepoints behave?
- What does select_for_update() do and when is it needed?
- What is ATOMIC_REQUESTS and what are its trade-offs?
- Why is catching exceptions inside atomic() dangerous?
MCQ Practice
1. What happens when an exception is raised inside a transaction.atomic() block?
An exception escaping the atomic block rolls back every database write made inside it, keeping data consistent.
2. Which setting wraps every view in a database transaction?
Setting ATOMIC_REQUESTS to True on a database wraps each request/view in a single transaction.
3. select_for_update() is used to?
select_for_update() locks the matched rows for the duration of the transaction, preventing race conditions.
Flash Cards
Django's main transaction API? — transaction.atomic(), used as a decorator or context manager for all-or-nothing writes.
Default transaction mode? — Autocommit — each query commits immediately unless wrapped in atomic().
What triggers a rollback? — Any exception escaping the atomic() block rolls back all its writes.
Purpose of select_for_update()? — Locks the selected rows within a transaction to prevent concurrent modification.