Django Framework orM and Custom SQL Statement Mixed Transaction Control Operation

  • 2021-07-03 00:34:44
  • OfStack

This article describes the Django framework orM and custom SQL statement mixed transaction control operations. Share it for your reference, as follows:

It is better to control transactions with simple ORM or simple custom SQL statements. The Django transaction summary was covered in the previous article, but there was no mention of both ORM and custom SQL statements in the same method.

If it is a simple ORM, you can do this, assuming that model, User and Category have been defined.


from django.db import transaction
...
@commit_on_success
def save_test(request):
  user=User(name="aaa",age=30)
  user.save()
  cat=Category(id=2,name="cat001")
  cat.save()
  .......

commit will only happen if the program executes successfully and correctly. For example, if cat is saved incorrectly, user will be rolled back.

If it is a simple custom SQL statement, it can be implemented in the following ways


from django.db import connection, transaction
...
def batch_execsql(sqlarray):
  print sqlarray
  cursor = connection.cursor()
  ret=""
  try:
    for sql in sqlarray:
      cursor.execute(sql)
    transaction.commit_unless_managed()
  except Exception,e:
    ret=str(e)
  cursor.close()
  return ret
sqlarray=[]
sqlarray.append("insert into table .......")
sqlarray.append("update table set.......")
ret=batch_execsql(sqlarray)

In this way, the transaction of custom SQL statements is implemented, and if any one statement goes wrong, it will be rolled back.

So, what if ORM is mixed with custom SQL statements, which I have combined in my project. For example, in the following way


@commit_on_success
def save_company_callinfo(request):
  response=HttpResponse()
  try:
     #==orm  Saved part ======
     ....
     model1.save()
     ....
     model2.save()
     ...
     #== Customize SQL  Part ====
     sqlarray=[]
     sqlarray.append("insert into table .......")
     sqlarray.append("update table set.......")
     ret=batch_execsql(sqlarray)
     if len(ret)>0:
       transaction.rollback()
       response.write('{"status":"no","error":"%s"}' % ('add call information error',))
     else:
       response.write('{"status":"no","error":"%s"}' % ('',))
  except Exception,e:
     response.write('{"status":"no","error":"%s"}' % (str(e),))
  return response

The above process can be modified to my own needs. I use AJAX because I need it myself, but on the whole, ORM and custom SQL mixed transactions can be controlled in this way.

I hope this article is helpful to the Python programming based on Django framework.


Related articles: