Маршрутизатор не влияет на миграцию базы данных
Я пытаюсь использовать две базы данных (одну для моделей auth и одну для пользовательских моделей), следуя документам Django: Multiple databases, но когда я мигрирую, все идет в обе базы данных, auth_db и default. Я хотел бы использовать маршрутизатор для разграничения между ними, но я почти точно следовал документации и не получил желаемых результатов.
settings.py
INSTALLED_APPS = [
'api',
'api.authentication',
'api.dictionary',
'api.pdf',
'corsheaders',
'django.contrib.admin',
'django.contrib.admindocs',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'django_smtp_ssl',
'rest_framework',
'rest_framework_simplejwt',
'rest_framework_simplejwt.token_blacklist',
]
# ...
"""
Constants below are defined by retrieval w/ os.environ[] in a try/except KeyError block.
"""
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': DEFAULT_DATABASE_NAME,
'USER': DEFAULT_DATABASE_USER,
'PASSWORD': DEFAULT_DATABASE_PASSWORD,
'HOST': '',
'PORT': '',
'TEST': {
'DEPENDENCIES': ['admin_db'],
},
},
'admin_db': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': ADMIN_DATABASE_NAME,
'USER': ADMIN_DATABASE_USER,
'PASSWORD': ADMIN_DATABASE_PASSWORD,
'HOST': '',
'PORT': '',
'TEST': {
'DEPENDENCIES': [],
},
},
}
DATABASE_ROUTERS = ['api.authentication.routers.AdminDBRouter']
api/authentication/routers.py
class AdminDBRouter:
"""
A router to control all database operations on models in the authentication application, all and any dependent applications, and Django administrative applications.
"""
ROUTE_APP_LABELS = {
'admin',
'auth',
'authentication',
'contenttypes',
'sessions',
'sites',
'token_blacklist',
}
def db_for_read(self, model, **hints):
"""
Attempts to read models defined in any app in 'self.ROUTE_APP_LABELS' go to 'admin_db'.
"""
if model._meta.app_label in self.ROUTE_APP_LABELS:
return 'admin_db'
return None
def db_for_write(self, model, **hints):
"""
Attempts to write models defined in any app in 'self.ROUTE_APP_LABELS' go to 'admin_db'.
"""
if model._meta.app_label in self.ROUTE_APP_LABELS:
return 'admin_db'
return None
def allow_relation(self, obj1, obj2, **hints):
"""
Allow relations if a model in any app defined in 'self.ROUTE_APP_LABELS' is involved.
"""
if obj1._meta.app_label in self.ROUTE_APP_LABELS or \
obj2._meta.app_label in self.ROUTE_APP_LABELS:
return True
return None
def allow_migrate(self, db, app_label, model_name=None, **hints):
"""
Make sure any app in 'self.ROUTE_APP_LABELS' only appears in the 'admin_db' database.
"""
if app_label in self.ROUTE_APP_LABELS:
return db == 'admin_db'
return None
Как показано ниже, запуск миграций просто создает две идентичные базы данных со всеми включенными приложениями. Предполагается, что модели в приложениях api.dictionary и api.pdf должны быть перенесены в БД default, а все остальное включено в БД admin_db. Как этого можно добиться?