Database Atomic Operations
As an example:
A consumer in a merchant to swipe credit card consumption, the transaction is normal, the bank in the consumer's account minus the corresponding money, the merchant's account plus the corresponding amount. However, if the bank has deducted the money from the consumer's account, and has not added the corresponding money in the merchant's account, for some reason, the system or database is abnormal, then the money has been deducted from the consumer's account, but the merchant's account does not add the corresponding money, in this case, The best solution is to use the atomic operation of the database, which is the transaction of the database. Make sure that you either succeed at the same time or fail at the same time before you commit to the database.
How Django defaults to submitting to a database
The default behavior of Django is to run in autocommit mode. Each query is immediately committed to the database unless the transaction is active.
Django automatically uses transactions or savepoint to ensure the integrity of ORM operations that require multiple queries, especially delete () and update () query.
Perform a task after a transaction commits
Sometimes you need to perform operations related to the current database transaction, but only if the transaction is successfully committed. examples may include celery tasks, e-mail notifications, or cache invalidation
Django provides the On_commit () functions that register callback functions that should be executed after the transaction has been successfully committed
From django.db import Transactiondef do_something (): pass # Send a mail, invalidate a cache, fire off a celery TAS K, Etc.transaction.on_commit (do_something)
How Django Implements Transactions
From django.db import transactiondef Create (Request): try: With transaction.atomic (): models. Userinfo.objects.create (username= "stu01", email= "[email protected]") models. Group.objects.create (title= "python") except Exception as E: return HttpResponse ("error ....") return HttpResponse ("OK")
This allows two SQL statements to be inserted successfully or failed at the same time
Django Database transactions