使用 2 个数据库的 Django 迁移?

Django migration with 2 DBs?

我有数据库 db1db2。两个数据库的模式应该使用相同的迁移脚本创建。

Django 文档提到了 DATABASE_ROUTERS and RunPython,但到目前为止我没能成功。函数被调用,但从函数调用时 migrations.CreateModel() 没有影响:未创建 table。

迁移脚本:

# 0001_initial.py

def forwards(apps, schema_editor):
    if schema_editor.connection.alias == 'db1':
        print('This line is called!')
        migrations.CreateModel(
            name='MyModel',
            fields=[
                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                # ...
            ]
        )

class Migration(migrations.Migration):
    initial = True
    
    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.RunPython(forwards, hints={'target_db': 'db1'}),
    ]

路由器:

DatabaseRouter:
    # ...
    def allow_migrate(self, db, app_label, model_name=None, **hints):
        if 'target_db' in hints:
            return db == hints['target_db']
        return True

命令:

python manage.py migrate --database=db1

有什么想法吗?提前致谢!

migrations.CreateModel 不会在实例化时在数据库中创建模型。它应该出现在 operations 列表中,然后迁移系统将使用它来创建模型。此外,您无论如何都不应该手动编写此迁移!只需将模型的代码写在 models.py:

class MyModel(models.Model):
    # Your fields, etc.

接下来因为你的问题问的是如何控制哪个模型迁移到哪个数据库。这些任务应该在 Database router 中完成,特别是在 allow_migrate 方法中。您可以检查为 dbapp_labelmodel_name return 传递的值是否应将模型迁移到那里。例如:

class MyRouter:
    def db_for_read(self, model, **hints):
        ...

    def db_for_write(self, model, **hints):
        ...

    def allow_relation(self, obj1, obj2, **hints):
        ...

    def allow_migrate(self, db, app_label, model_name=None, **hints):
        # Suppose I want to migrate all models from the app 'some_app' to 'db1' only.
        if app_label in ['some_app']:
            return db == 'db1'
        # Suppose I want to migrate 'MyModel' to 'db2' only.
        if model_name == 'mymodel':  # 'mymodel' is lowercase 'MyModel'
            return db == 'db2'
        return None