Full answer
A transaction makes several database changes behave as one. Paying a canteen bill might need two changes: subtract from the student's wallet and insert a payment row. If the second fails after the first succeeded, the data is wrong. A transaction prevents that.
Django defaults:
- Autocommit: every query commits immediately unless you are inside
atomic(). ATOMIC_REQUESTS = True(per database) wraps every view in a transaction. Simple, but it holds a transaction open for the whole request, including slow template rendering or API calls.
transaction.atomic() works as a decorator or a context manager:
with transaction.atomic():
wallet.balance = F("balance") - 120
wallet.save()
Payment.objects.create(...)If an exception leaves the block, Django rolls back. If the block ends normally, it commits.
Nesting: an inner atomic() creates a savepoint. If the inner block fails and you catch the exception outside it, only the inner work is undone and the outer transaction can continue. Do not catch database errors inside an atomic block and keep querying; wrap the risky part in its own inner atomic() instead.
transaction.on_commit(func) runs func after the outermost transaction commits, and never if it rolls back. Without it, a Celery task could start before the row it needs is visible, or a "payment received" email could go out for a payment that was rolled back. Outside any transaction the callback runs immediately. Django 5.0 added robust=True so one failing callback does not stop the others.
In tests, TestCase wraps each test in a transaction that never commits, so use self.captureOnCommitCallbacks(execute=True) to run on_commit callbacks.
import sys
import types
import django
from django.conf import settings
# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__
settings.configure(
SECRET_KEY="demo-only-key-not-for-production",
ALLOWED_HOSTS=["testserver"], # the host name used by Django's test client
INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()
from django.db import models, connection, transaction, IntegrityError
from django.db.models import F
class Wallet(models.Model):
student = models.CharField(max_length=30, unique=True)
balance = models.IntegerField()
class Meta:
app_label = "school"
class Payment(models.Model):
student = models.CharField(max_length=30)
amount = models.IntegerField()
class Meta:
app_label = "school"
with connection.schema_editor() as editor:
editor.create_model(Wallet)
editor.create_model(Payment)
Wallet.objects.create(student="rohan", balance=500)
sent = []
def pay(student, amount, fail=False):
with transaction.atomic():
Wallet.objects.filter(student=student).update(balance=F("balance") - amount)
Payment.objects.create(student=student, amount=amount)
transaction.on_commit(lambda: sent.append(f"receipt {amount}"))
if fail:
raise RuntimeError("card machine offline")
pay("rohan", 120)
try:
pay("rohan", 200, fail=True)
except RuntimeError:
pass
print(Wallet.objects.get().balance, Payment.objects.count(), sent)
# Savepoint: the inner failure is undone, the outer work survives
with transaction.atomic():
Payment.objects.create(student="rohan", amount=1)
try:
with transaction.atomic():
Wallet.objects.create(student="rohan", balance=0) # duplicate -> IntegrityError
except IntegrityError:
print("duplicate wallet rolled back to savepoint")
print(Payment.objects.count())
Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): 380 1 ['receipt 120'] duplicate wallet rolled back to savepoint 2
Key points
- Autocommit by default; atomic() groups changes
- Exceptions inside atomic() roll back
- Nested atomic() uses savepoints
- on_commit callbacks run only after a successful commit
- Avoid ATOMIC_REQUESTS for slow views
Common mistakes
- Sending emails or queueing tasks inside a transaction without on_commit
- Catching IntegrityError inside atomic() and continuing without an inner savepoint
- Turning on ATOMIC_REQUESTS and holding transactions open during slow work
- Testing on_commit logic in TestCase without captureOnCommitCallbacks
Follow-ups
- What is the difference between atomic() and select_for_update()?
- What isolation level does PostgreSQL use by default and why does it matter?
- How would you make a payment handler idempotent?
Tips
- Use a money example to show why atomicity matters
- Explain savepoints with nested atomic()
- Mention on_commit for side effects, it is a strong signal of real experience