Django transactions ensure data integrity with atomic operations.
1from django.db import transaction23# Atomic block4@transaction.atomic5def transfer_money(from_account, to_account, amount):6 from_account.balance -= amount7 from_account.save()89 to_account.balance += amount10 to_account.save()11 # If any error, both operations are rolled back1213# Manual atomic block14with transaction.atomic():15 user = User.objects.create(name="Alice")16 profile = Profile.objects.create(user=user)17 # Both succeed or both fail1819# Savepoints20with transaction.atomic():21 user = User.objects.create(name="Alice")2223 with transaction.atomic():24 # Savepoint25 profile = Profile.objects.create(user=user)26 # If this fails, only profile is rolled back2728# Using in views29from django.db import transaction3031@transaction.atomic32def my_view(request):33 # Entire view is atomic34 pass3536# Select for update (locking)37with transaction.atomic():38 user = User.objects.select_for_update().get(id=1)39 user.balance += 10040 user.save()
When to use: