Когда необходимо использовать schema_editor.connection.alias в методе django migrations.RunPython? - PullRequest
1 голос
/ 29 мая 2020

Когда необходимо использовать schema_editor.connection.alias в методе migrations.RunPython и почему?

При использовании Run Python в переносе данных 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 Python не изменяет магическим образом соединение моделей для тебя; любые вызываемые вами методы модели будут go в базе данных по умолчанию, если вы не дадите им текущий псевдоним базы данных (доступен из 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),
    ]
...