2010-11-28 11 views
0

DjangoのORM +カスタムRaw SQLを使用してバルク挿入スクリプトを作成しています。コードは以下の概要があります。Django:管理されたraw dbコミットの混在 - TransactionManagementError

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

どのように私はこの問題を解決することができます。

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() 

を私は次のエラーを取得しておきますか?

+0

サンプルコードにいくつかの条件を含めることを忘れていないと、最後のcommit()が実行されませんでしたか? – knutin

+0

はい、私は確信しています:) – Jonathan

答えて

0

回避策を試すことができます - transaction.commit()の直後にmodel_1.save()の後に配置してください。あなたは、生とORMのトランザクションを分離する必要があると思います。

1

同様の状況でこの例外が発生し始めました。 django ORMは実際にdjango.core.exceptions.ValidationErrorエラーを投げていました。これは、日付の形式が正しくないためです。データベース処理をバッチ処理するために手動トランザクション処理を使用していたため、Djangoトランザクション処理コードは、発生したdjango.core.exceptions.ValidationError例外の内部をクリーンアップしようとしていましたが、django.db.transaction.TransactionManagementError例外を投げました。他の例外がスローされているかどうかを確認するには、model_1コードのtry/exceptを試してください。作成コードをオブジェクトへの入力データに問題があるかどうかを確認するために

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

:ような何か。

関連する問題