在第二个数据库上运行Python迁移

kad*_*dir 5 django django-migrations

使用 RunPython 在第二个数据库上运行数据库迁移失败

python3 manage.py migrate --database=app
Run Code Online (Sandbox Code Playgroud)

问题是 apps.get_model 方法采用已经具有最新迁移的默认数据库。

不起作用:

def copy_cpr_cents_to_euros(apps, schema_editor):
    User = apps.get_model('accounting', 'User')
    User.objects.filter(...);
Run Code Online (Sandbox Code Playgroud)

作品:

def copy_cpr_cents_to_euros(apps, schema_editor):
    User = apps.get_model('accounting', 'User')
    User.objects.using('app').filter(...);
Run Code Online (Sandbox Code Playgroud)

有没有办法在迁移中使用给定的数据库,因此在这种情况下“app”无需明确声明它,因为它应该适用于两个数据库?

所以像这样:

User.objects.using(database_name).filter(...)
Run Code Online (Sandbox Code Playgroud)

kad*_*dir 6

schema_editor.connection.alias
Run Code Online (Sandbox Code Playgroud)

包含开始迁移的当前数据库的字符串。

因此每个 RunPython 迁移都必须使用此别名来手动选择正确的数据库。

例子:

def copy_cpr_cents_to_euros(apps, schema_editor):
    User = apps.get_model('accounting', 'User')
    db = schema_editor.connection.alias
    User.objects.using('app').using(db).filter(...)
Run Code Online (Sandbox Code Playgroud)