使用多个数据库时运行makemigrations

时间:2017-09-15 22:11:24

标签: django

我已经设置了我的Django项目以使用两个数据库。一个是只读的,另一个是"默认" django数据库用于项目的其余部分。

以下是设置:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'sipf',
        'USER': 'myusername',
        'PASSWORD': 'secret',
        'HOST': '127.0.0.1',
        'PORT': '5432',
    }
    ,
    'my_read_only_db': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'my_read_only_db',
        'USER': 'myusername',
        'PASSWORD': 'mypassword',
        'HOST': 'remote.host.edu',
    }
}

这是只读DB的router.py:

class MyReadOnlyDBRouter(object):

    def db_for_read(self, model, **hints):
        if model._meta.app_label == 'my_read_only_db':
            return 'my_read_only_db'
        return None

和默认数据库:

class PrimaryRouter(object):
    def db_for_read(self, model, **hints):
        return 'default'

    def db_for_write(self, model, **hints):
        return 'default'

    def allow_relation(self, obj1, obj2, **hints):
        db_list = 'default'
        if obj1._state.db in db_list and obj2._state.db in db_list:
            return True
        return None

    def allow_migrate(self, db, app_label, model_name=None, **hints):
        return True

最后是设置中的路由:

DATABASE_ROUTERS = ['my_read_only_db.router.MyReadOnlyDBRouter', 'common.router.PrimaryRouter']

据我所知,在运行迁移时,需要指定要运行的数据库,如下所示:

$ ./manage.py migrate --database=default

然而,在达到目标之前,需要运行makemigrations。在这里,它显然是在尝试在只读数据库中创建表,并且我得到了:

django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create the django_migrations table ((1142, "CREATE command denied to user 'user'@'example.com' for table 'django_migrations'"))

虽然它甚至不应该尝试这样做,因为django_migrations表应该在具有写入能力的默认数据库中。

1 个答案:

答案 0 :(得分:1)

从Django源代码django/core/management/commands/makemigrations.py

# Non-default databases are only checked if database routers used.
aliases_to_check = connections if settings.DATABASE_ROUTERS else [DEFAULT_DB_ALIAS]
for alias in sorted(aliases_to_check):
    connection = connections[alias]
    if (connection.settings_dict['ENGINE'] != 'django.db.backends.dummy' and any(
            # At least one model must be migrated to the database.
            router.allow_migrate(connection.alias, app_label, model_name=model._meta.object_name)
            for app_label in consistency_check_labels
            for model in apps.get_app_config(app_label).get_models()
    )):
        loader.check_consistent_history(connection)

如果您使用的是数据库路由器,它将尝试检查每个数据库连接的历史记录是否一致。如果通过注释掉配置暂时禁用数据库路由器或只读数据库,则可以在不建立数据库连接的情况下运行makemigrations,然后可以将其重新添加。