How do you implement database transactions in Django?
Instruction: Explain the mechanisms Django provides for managing database transactions.
Context: This question probes the candidate's understanding of transaction management in Django and their ability to ensure data integrity.
Updated
Official answer available
Read the opening below, then unlock the full answer and practical guidance.
Django defaults to autocommit, not a transaction around every view. transaction.atomic() supplies an explicit boundary for related database changes on one connection. Successful exit of the outermost block commits; an exception that escapes it rolls back its changes. Nested atomic blocks normally use savepoints.
For a fictional order and its lines, write both inside one atomic block so a failed line insert does not leave a committed incomplete order. Catch database exceptions outside the atomic block that should roll back...