Junior — Middle
How to implement transaction management in Django to ensure data integrity?
sobes.tech AI
Answer from AI
In Django, transaction management is handled using the django.db.transaction module. To ensure data integrity, you can use the @transaction.atomic decorator or the transaction.atomic() context manager. They create an atomic block where all operations either succeed or are rolled back if an exception occurs.
Example of usage:
from django.db import transaction
def my_view(request):
with transaction.atomic():
# database operations
obj = MyModel.objects.create(name='example')
# if an exception occurs here, all changes will be rolled back
Or with a decorator:
from django.db import transaction
@transaction.atomic
def my_function():
# database operations
pass
This guarantees that the data remains in a consistent state, even if errors occur during execution.