我正在使用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
我怎樣才能解決這個問題?
你確定你沒有錯過在示例代碼中包含一些條件,這會導致最後的commit()不能運行嗎? – knutin 2010-11-28 08:48:47