Junior — Middle
Explain how to implement transaction management when working with a database using Django ORM.
sobes.tech AI
Answer from AI
In Django ORM, transaction management is implemented using the context manager transaction.atomic(). It allows grouping multiple database operations into a single transaction, which will either be fully completed or rolled back in case of an error.
Example of usage:
from django.db import transaction
try:
with transaction.atomic():
# Perform several database operations
obj1.save()
obj2.save()
# If an exception occurs here, all changes will be rolled back
except Exception as e:
# Error handling
print(f"Transaction error: {e}")
You can also use the @transaction.atomic decorator for functions, so that all their code runs within a transaction.
This guarantees data integrity and prevents partial changes in case of errors.