什么时候需要在 django `migrations.RunPython` 方法中使用 `schema_editor.connection.alias` ?

43T*_*cts 9 django django-migrations

schema_editor.connection.alias什么时候需要在方法中使用它migrations.RunPython,为什么?

在数据迁移中使用 RunPython 时,django 建议您应该使用schema_editor.connection.alias

from django.db import migrations

def forwards_func(apps, schema_editor):
    # We get the model from the versioned app registry;
    # if we directly import it, it'll be the wrong version
    Country = apps.get_model("myapp", "Country")
    db_alias = schema_editor.connection.alias
    Country.objects.using(db_alias).bulk_create([
        Country(name="USA", code="us"),
        Country(name="France", code="fr"),
    ])

class Migration(migrations.Migration):

    dependencies = []

    operations = [
        migrations.RunPython(forwards_func, reverse_func),
    ]
Run Code Online (Sandbox Code Playgroud)

警告

RunPython不会神奇地为您改变模型的连接;您调用的任何模型方法都将转到默认数据库,除非您为它们提供当前数据库别名(可从 获得schema_editor.connection.alias,其中schema_editor是函数的第二个参数)。*

但是描述数据迁移的文档部分根本没有提到alias

from django.db import migrations

def combine_names(apps, schema_editor):
    # We can't import the Person model directly as it may be a newer
    # version than this migration expects. We use the historical version.
    Person = apps.get_model('yourappname', 'Person')
    for person in Person.objects.all():
        person.name = '%s %s' % (person.first_name, person.last_name)
        person.save()

class Migration(migrations.Migration):

    dependencies = [
        ('yourappname', '0001_initial'),
    ]

    operations = [
        migrations.RunPython(combine_names),
    ]
Run Code Online (Sandbox Code Playgroud)