gpt4 book ai didi

django - 使用多个数据库时运行 makemigrations

转载 作者:行者123 更新时间:2023-12-02 06:46:59 27 4
gpt4 key购买 nike

我已将 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',
}
}

这是只读数据库的 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']

我知道运行 migrate 时需要指定要运行的数据库,如下所示:

$ ./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 表应该位于具有写入功能的默认数据库中。

最佳答案

来自 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 而无需建立数据库连接,然后您可以将它们添加回来。

关于django - 使用多个数据库时运行 makemigrations,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46248065/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com