When you write data to a database, you inadvertently write incomplete data, which we call dirty data. Transaction management (transaction) can prevent this from happening. Transaction management Once a write exception is detected, a rollback operation is performed, either writing the full data or not writing it. The use of transactions in Django is simple:
1. New project transaction, create app App01, edit models Create two tables and perform a database migration as follows:
from Import Models class UserInfo (models. Model): = models. Charfield (max_length=32) = models. Emailfield (max_length=64)class Dept (models. Model): = models. Charfield (MAX_LENGTH=32)
2. Define the route:
from Import URL from Import = [ url (r'^test/$', Views.test),]
3. Define the test view function;
fromDjango.shortcutsImportRender, HttpResponse from.ImportModelsdefTest (Request):Try: fromDjango.dbImportTransaction#Import TransactionsWith transaction.atomic (): User_obj= Models. UserInfo.objects.create (username='Lena', email='[email protected]') Dept_obj= Models. Dept.objects.create (title='IT') exceptException as E:returnHttpResponse ('error happened, DB rollback') returnHttpResponse ('OK')
Description
- The above combines the created
user_obj
and dept_obj
recorded behavior into an indivisible atomic operation that performs a rollback operation if any exception occurs in the database operation performed within the atom.
- Things are checked for exception rollback, but not fault-tolerant, errors are thrown, so here is an exception catch.
- Normal access
http://127.0.0.1:8000/test/
, will get an OK response, if we manually dept_obj = models.Dept.objects.create(title=‘IT‘)
change to title=‘IT‘
name=‘IT‘
, manually caused the exception, then the thing will trigger rollback, write user_obj
will also be revoked. This allows you to view database validation.
Note : Transactions require support from the database engine, such as the InnoDB engine.
The Django database complements the business