#python #django
#python #django
Вопрос:
Мне нужно изолировать базу данных приложений django по умолчанию (auth, contenttypes, sessions), я прочитал в документации [Несколько баз данных] [1] все понятно и хорошо объяснено, но для меня не работает: (
settings.py
DATABASES = {
'default_django': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
},
'default': {
'ENGINE': 'django.contrib.gis.db.backends.postgis',
'OPTIONS': {
'options': '-c search_path=eos,public'
},
'NAME': '****',
'USER': '*****',
'PASSWORD': '****',
'HOST': 'localhost',
'PORT': '5432',
}
}
DATABASE_ROUTES = ['core.dbrouter.AuthRoute', 'core.dbrouter.GisRoute']
и ./core/dbrouter.py
class AuthRouter:
"""
A router to control all database operations on models in the
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
"""
route_app_labels = {
'auth', 'admin', 'contenttypes',
'sessions', 'messages', 'staticfiles'
}
def db_for_read(self, model, **hints):
"""
Attempts to read auth and contenttypes models go to auth_db.
"""
if model._meta.app_label in self.route_app_labels:
return 'default_django'
return None
def db_for_write(self, model, **hints):
"""
Attempts to write auth and contenttypes models go to auth_db.
"""
if model._meta.app_label in self.route_app_labels:
return 'default_django'
return None
def allow_relation(self, obj1, obj2, **hints):
"""
Allow relations if a model in the auth or contenttypes apps 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 the auth and contenttypes apps only appear in the
'auth_db' database.
"""
if app_label in self.route_app_labels:
return db == 'default_django'
return None
Когда я это делаю python3 manage.py migrate
, это показывает
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
No migrations to apply.
Пожалуйста, кто-нибудь может объяснить?(Почему?)
[1]: https://docs.djangoproject.com/en/3.1/topics/db/multi-db /
Комментарии:
1. Вы пытались указать DB ?
python3 manage.py migrate --database=default_django
? Из документов «По умолчанию он работает с базой данных по умолчанию»2. Да, это работает, но тогда зачем мне использовать маршрутизаторы?
3. Я думал, что маршрутизаторы автоматически обрабатывают это?
4. Маршрутизатор автоматически обрабатывает его для остальной части доступа к БД. Запрашивать чтение / запись и т.д.
5. Хорошо, чисто! Спасибо!
Ответ №1:
ты забыл букву » Р » .
DATABASE_ROUTES = ['core.dbrouter.AuthRoute', 'core.dbrouter.GisRoute']
↓
DATABASE_ROUTERS = ['core.dbrouter.AuthRoute', 'core.dbrouter.GisRoute']