Зміст курсу
Django ORM Ninja: Advanced Techniques for Developers
Django ORM Ninja: Advanced Techniques for Developers
Transactions Basics
In database management, a transaction is a sequence of operations performed as a single, indivisible unit of work. Django ORM provides robust support for transactions, ensuring data integrity and consistency in line with ACID (Atomicity, Consistency, Isolation, Durability) principles.
Understanding ACID
- Atomicity: ensures that all operations within a transaction are completed successfully; if not, the transaction is aborted;
- Consistency: guarantees that a transaction transforms the database from one valid state to another;
- Isolation: ensures that concurrent execution of transactions leaves the database in the same state as if the transactions were executed sequentially;
- Durability: once a transaction is committed, it will remain so, even in the event of a system failure.
Let's consider two scenarios: one with incorrect transaction handling leading to potential data inconsistency, and another with correct usage of transactions ensuring data integrity.
Let's imagine that Anna wants to transfer $200 from her account to John. However, during the transaction, something went wrong, and Anna's power and internet connection were cut off, resulting in an error processing this money transfer. When the power and internet were restored, she saw that the money had been debited from her account, but John had not received it. This error led to data inconsistency. So, what should be done?
In the bank's system, the developers used ACID transaction rules. The function responsible for money transfers utilized the built-in @transaction.atomic
decorator, which ensures the complete reversal of actions taken by that function. This means that if a failure occurs at any point in the function before its completion, all previous actions of the function are reversed, and Anna does not lose her money due to the failure. She can safely retry the transaction later. The consistency of the data in the database is maintained, and all changes in it remain consistent over time.
Дякуємо за ваш відгук!