A database transaction is a transaction process that comprises of a unit of work which is performed with a database through database management system. Each transaction is treated in a reliable and coherent way independent of other transactions. A database transaction must be atomic, consistent, isolated and durable, i.e., it must follow the ACID property. It must follow a simple logic of “All or nothing” which means each unit of work must either have completed working fully on the database or should have no effect on the database. Also each transaction must be isolated from the other transactions.
In SQL we have the distributed transactions, transactional file systems, managing database transactions, etc. In this the transactional property is invoked inherently, i.e., as soon as one transaction ends, another gets started automatically.
It works like this: Before calling a view function, Django starts a transaction. If the response is produced without problems, Django commits the transaction. If the view produces an exception, Django rolls back the transaction.
Transactions in a database environment have two main purposes:
1. The first one is to provide reliable units of work that allow correct recovery from the failures and keep the database consistent even in cases of system failures. This is so because when any execution stops (completely or partially), many other operations upon a database which were related to that execution remains incomplete, i.e., with unclear status.
2. The second one is to provide isolation between the programs which are accessing the database concurrently. If this isolation is not provided, the outcome of the program would be possibly erroneous.
Django’s default transaction behavior
Django’s default behavior is to run in auto-commit mode. Each query is immediately committed to the database.
See below for details:
Django uses transactions or save points automatically to guarantee the integrity of Operational Risk Management (ORM) operations that require multiple queries, especially the DELETE and UPDATE queries.
Changes in Django 1.6:
Previous version of Django featured a more complicated default behavior.
Django gives you a few ways to control how database transactions are managed, if you’re using a database that supports transactions.
Django’s default behavior is to run with an open transaction which it commits automatically when any built-in, data-altering model function is called. For example, if you call model.save() or model.delete(), the change will be committed immediately.
This is much like the auto-commit setting for most databases. As soon as you perform an action that needs to write to the database, Django produces the INSERT / UPDATE / DELETE statements and then does the COMMIT. There is no implicit ROLLBACK.
The recommended way to handle transactions in Web requests is to tie them to the request and response phases via Django’s Transaction Middleware.