2010-11-28 49 views
0

我正在使用Django的ORM +自定義原始SQL編寫批量插入腳本。該代碼具有以下大綱:Django:混合管理和原始數據庫提交 - TransactionManagementError

import sys, os 
from django.core.management import setup_environ 
from my_project import settings 
from my_project.my_app.models import Model1, Model2 
setup_environ(settings) 
from django.db import transaction 
from django.db import connection 

@transaction.commit_manually 
def process_file(relevant_file): 

    data_file = open(relevant_file,'r') 

    cursor = connection.cursor() 

    while 1: 
     line = data_file.readline() 
     if line == '': 
      break 

     if not(input_row_i%1000): 
      transaction.commit() 

     if ([some rare condition]): 
      model_1 = Model1([Some assignments based on line]) 
      model_1.save() 

     values = [Some values based on line] 
     cursor.execute("INSERT INTO `table_1` ('field_1', 'field_2', 'field_3') VALUES (%i, %f, %s)", values) 

    data_file.close() 
    transaction.commit() 

我不斷收到以下錯誤:

django.db.transaction.TransactionManagementError: Transaction managed block ended with pending COMMIT/ROLLBACK 

我怎樣才能解決這個問題?

+0

你確定你沒有錯過在示例代碼中包含一些條件,這會導致最後的commit()不能運行嗎? – knutin 2010-11-28 08:48:47

回答

0

您可以嘗試一種解決方法 - 在model_1.save()之後放置一個transaction.commit()。我認爲你需要隔離原始和ORM交易。

1

我開始在類似的情況下得到這個例外。由於日期格式不正確,django ORM實際上正在拋出django.core.exceptions.ValidationError錯誤。因爲我正在使用手動事務處理批量寫入數據庫,所以Django事務處理代碼試圖清除引發的django.core.exceptions.ValidationError異常,並拋出了它自己的django.db.transaction.TransactionManagementError異常。試一試/除了你的model_1代碼外,看是否有其他異常被拋出。例如:

try: 
    model_1 ... 
    model_1.save() 
except: 
    print "Unexpected error:", sys.exc_info()[0] 
    print 'line:', line 

查看輸入數據是否存在與對象創建代碼有關的任何問題。