2015-04-13 6 views
5

Django 1.5 दिनों, अगर मैं मैन्युअल रूप से (लेन-देन के भीतर या लेन-देन) लेनदेन के प्रबंधन करना चाहता था में, मैं कुछ इस तरह करना होगा:Django 1.6 - "बाहरीतम परमाणु 'ब्लॉक autocommit बंद होने पर savepoint = गलत का उपयोग नहीं कर सकता है।"

@transaction.commit_manually 
def my_method(): 
    master_sid = transaction.savepoint() 
    for item in things_to_process: 
     inner_sid = transaction.savepoint() 
     # Make changes, save models, etc. 
     ... 
     if I_want_to_keep_this_iterations_changes: 
      transaction.savepoint_commit(inner_sid) 
     else: 
      transaction.savepoint_rollback(inner_sid) 
    if I_want_to_keep_all_un_rolled_back_changes_from_loop: 
     transaction.savepoint_commit(master_sid) 
    else: 
     transaction.savepoint_rollback(master_sid) 

अगर मैं सही ढंग से समझने the Django docs रहा हूँ, जब 1.6 Django के उन्नयन Django 1.6+ में

def my_method(): 
    transaction.set_autocommit(False) 
    try: 
     # Same code as above 
    finally: 
     transaction.set_autocommit(True) 

हालांकि,, यदि आप model.save() जबकि autocommit गलत है कहते हैं, Django निम्न त्रुटि बढ़ा देंगे:: +, मैं ऊपर कुछ करने के लिए इस तरह बदलना चाहिए

TransactionManagementError: The outermost 'atomic' block cannot use savepoint = False when autocommit is off.

तो, ऑटोोकॉमिट गलत होने पर मैं मॉडल को कैसे सहेजूं? मेरे पुराने, Django 1.5 कोड के लिए आधुनिक प्रतिस्थापन क्या है?

+0

विधि पर @ banking.atomic का उपयोग करें – GrvTyagi

उत्तर

4

आप transaction.atomic (का उपयोग करना चाहिए) बजाय:

def my_method(): 
    with transaction.atomic(): 
     for item in things_to_process: 
      with transaction.atomic(): 
       # Make changes, save models, etc. 
       ... 
       if I_want_to_roll_back_this_iterations_changes: 
        raise Exception('inner rollback') 
     if I_want_to_roll_back_changes_from_loop: 
      raise Exception('mater rollback') 

transaction.atomic() संभाल लेंगे प्रतिबद्ध और रोलबा सीके, और यह घोंसला जा सकता है।

Relevant docs

-1

आपको controlling transactions explicitly पढ़ना चाहिए।

विशेष रूप से

If you attempt to run database queries before the rollback happens, Django will raise a TransactionManagementError. You may also encounter this behavior when an ORM-related signal handler raises an exception.

और

You may use atomic when autocommit is turned off. It will only use savepoints, even for the outermost block, and it will raise an exception if the outermost block is declared with savepoint=False.

संबंधित मुद्दे