django - When is it required to use `schema_editor.connection.alias` in a django `migrations.RunPython` method?
问题描述
When is it required to use schema_editor.connection.alias
in a migrations.RunPython
method and why?
When using RunPython in a data migration, django advises that you should use 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),
]
Warning
RunPython does not magically alter the connection of the models for you; any model methods you call will go to the default database unless you give them the current database alias (available from
schema_editor.connection.alias
, whereschema_editor
is the second argument to your function).*
But the docs section that describes data migrations, it doesn't mention the alias
at all:
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),
]
解决方案
推荐阅读
- python - 使用 daphne 部署 Django 事件流
- c# - using 语句中的标准库没有任何自动完成功能是 vs 代码 1.61.0
- c++ - 运行第一个 gtest 示例时出现问题
- assembly - Nasm ld 重定位被截断以适应:R_X86_64_16
- javascript - 是否有可能在拉斐尔饼图的图例中添加卷轴?
- swift - 如何从 HealthKit 获取体脂百分比数据?
- java - 大批
- 获取单词在行号上的字符位置 - sql - 未使用 Snowflake 中的搜索优化服务
- amazon-web-services - 如何使用 AWS 生命周期管理策略仅将大于 100MB 的对象从 S3 Standard 转换到 AWS Glacier?
- javascript - 在javascript中循环对象数组