SoFunction
Updated on 2024-11-10

django framework transaction processing summary [ORM transactions and raw sql, customize sql transaction processing].

This article example tells about django framework transaction processing. Shared for your reference, as follows:

There are two scenarios where transactions are required in django.

1. transaction processing based on django orM

2. It is based on the processing of custom SQL statements of the transaction, usually more complex SQL, with ORM processing is not convenient when used. Or a large number of SQL statement execution, more concerned about the efficiency of the case with.

First of all, let's talk about the second case, because this case is relatively simple, do not ORM so many things, with a method I wrote to explain

from  import connection, transaction
.....
def batch_execsql(sqlarray):
  cursor = () # Get the processed cursor object
  ret=""
  try:
    for sql in sqlarray:
      (sql)
    transaction.commit_unless_managed() # This is the point, without this statement, there is no commit.
  except Exception,e: # Simple exception handling, can be ignored.
    ret=str(e)
  ()
  return ret #Returns an exception if there is an exception, otherwise returns the empty string.

As you can see from the abovetransaction.commit_unless_managed()This is the way to handle transactions in the case of custom SQL statements. The sqlarray in the above example represents a list with a number of self-written SQL statements that are required to be completed in a transaction.

Let's take a look at the first scenario, the handling of transactions when using the ORM. This is described in the official django documentation, which is briefly translated below.

1. django default transaction, is automatically processed, when you call orM's (), (), all changes will be immediately committed, equivalent to the database set auto commit, no hidden rollback.

2. Transaction interception of http requests , this is the recommended way to use the transaction middleware to complete , this is a better way , but must be configured in the .

MIDDLEWARE_CLASSES = (
  '',
  '',
  '',
  '',
  '',
)

However, it is important to note that the order in which your middleware is configured after this configuration is highly relevant. All middleware after TransactionMiddleware is subject to transaction control. So when you put the session middleware after the Transaction, it will also be affected. However, theCacheMiddleware, UpdateCacheMiddleware, and FetchFromCacheMiddleware will not be affected, the cache mechanism has its own way of handling this, using the internal connection for

In addition, TransactionMiddleware is only valid for default database configuration, if you want to use this way for another data connection, you must implement your own middleware.

3. To control their own transactions , in this case , you have the flexibility to control their own transactions . In the middle of the TransactionMiddleware middleware is not configured , the basic use of decorative patterns to achieve .

a) @ , django's default transaction processing, using this decorative pattern will ignore the global transaction settings

from  import transaction
@
def viewfunc(request):
  ....
@(using="my_other_database")
def viewfunc2(request):
  ....

b) @transaction.commit_on_success In a method, the transaction is committed when all the work is done.

from  import transaction
@transaction.commit_on_success
def viewfunc(request):
  ....
@transaction.commit_on_success(using="my_other_database")
def viewfunc2(request):
  ....

c) commit_manually() , which handles it entirely on its own, but if you don't call thecommit()orrollback(), will throw theTransactionManagementError Exception.

from  import transaction
@transaction.commit_manually
def viewfunc(request):
  ...
  # You can commit/rollback however and whenever you want
  ()
  ...
  # But you've got to remember to do it yourself!
  try:
    ...
  except:
    ()
  else:
    ()
@transaction.commit_manually(using="my_other_database")
def viewfunc2(request):
  ....

I hope that what I have said in this article will help you in designing Python programs based on Django framework.