简体   繁体   中英

Does try/except block causes commit_on_success to fail

@transection.commit_on_success
def recordIt(...)
   try:
       ....
       recordable = firstDataInsertionFunction(...)
       if recordable:
          myRec = SecondDataInsertion(.....)

    except:
       ....

As for commit_on_success , if my second data insertion fails, django must automatically rollback, so my first data insertion will be rolled back too...

But this is not working, and first inserted data is saved to db, while i could not see the result of second insertion on my database... Is try/except causes commit_on_success to fail? Because as documentation says:

If the function returns successfully, then Django will commit all work done within the function at that point. If the function raises an exception, though, Django will roll back the transaction.

And try handles all exceptions. Is is the problem of my not working commit_on_success ?

First of all, don't ever do except: . It's just bad, and catches too much, and hides bugs.

And yes, if you handle the exception, then commit_on_success cannot possibly know there was an error. If you need to run logic on exception, reraise it afterwards (just raise , with no argument). Or rollback yourself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM