2015-09-03 9 views

答えて

0

この情報は、Migrationクラスでは提供されていません。RunPython操作に渡されるschema_editor属性で提供されています。これを使用する例については、the documentationを参照してください。

4

私はまさに同じ必要性を持っていました。 postgresでは動作するが、sqliteでは動作しないシーケンスの初期値を設定する移行を編集しなければならなかった。 Danielがリンクしているドキュメントに従ってRunPythonの中でRunSQLをラップする方法は次のとおりです。

from django.db import migrations 


def forwards(apps, schema_editor): 
    if not schema_editor.connection.vendor == 'postgres': 
     return 
    migrations.RunSQL(
     "alter sequence api_consumer_id_seq restart with 1000500;") 


class Migration(migrations.Migration): 
    dependencies = [ 
     ('api', '0043_auto_20160416_2313'), 
    ] 

    operations = [ 
     migrations.RunPython(forwards), 
    ] 
+1

マイベンダー文字列が 'postgresql'としない(ジャンゴ1.10.6で)' postgres' –

+0

たこれに伴う問題は 'migrations.RunSQLは()'オブジェクトを返すことです。そのオブジェクトの '_run_sql()'メソッドが特定のパラメータで呼び出されるまで、実際にはSQLを実行しません。 'migrations.RunPython()'メソッドも使用するが、実際にSQLを実行する方法でSQLを実行するソリューションのPaulMestの回答を参照してください。 – radicalbiscuit

3

今日は同様の問題を解決 - だけPostgresのDBのため、新しいモデルを作成するために、移行を実行するために必要 - と、私はこの質問を見つけました。しかし、マタイの答えは私を助けませんでした。実際、私はそれがまったく機能しているかどうかはわかりません。これは、migrations.RunSQL(...)の行が実際にはを実行しないためです。 SQL; CommandのタイプRunSQLの新しいオブジェクトを作成し、すぐに破棄します。ここで

​​
4

私はRunSQLを得ることができなかったので、私はこの問題を解決する方法である:ここでは

は、私は誰もが将来的に「条件付きの移行をジャンゴ」を検索しようとする場合には、問題を解決することになった方法です内部で働くことRunPython。ありがたいことに、schema_editorオブジェクトにはexecute() methodがあります。

def forwards(apps, schema_editor): 
    if not schema_editor.connection.vendor.startswith('postgres'): 
     logger.info('Database vendor: {}'.format(schema_editor.connection.vendor)) 
     logger.info('Skipping migration without attempting to ADD CONSTRAINT') 
     return 

    schema_editor.execute('ALTER TABLE my_table ADD CONSTRAINT my_constraint (my_field != \'NaN\';)') 


def backwards(apps, schema_editor): 
    if not schema_editor.connection.vendor.startswith('postgres'): 
     logger.info('Database vendor: {}'.format(schema_editor.connection.vendor)) 
     logger.info('Skipping migration without attempting to DROP CONSTRAINT') 
     return 

    schema_editor.execute('ALTER TABLE my_table DROP CONSTRAINT my_constraint;') 


class Migration(migrations.Migration): 

    dependencies = [ 
     ... 
    ] 

    operations = [ 
     migrations.RunPython(forwards, backwards, atomic=True) 
    ] 
+0

atomic = Falseにする必要があることを除いて、これは私のために働いた – kzh

+0

'atomic = False'に注意してください。いくつかのアクションが成功し、他のアクションが失敗すると、データベースは矛盾した状態になる可能性があります。 – PaulMest

+0

Djangoはそうでなければ私のためにそれを実行することを拒否します。 – kzh