python - 如何在 Django 中使用多个数据库 [使用数据库路由器]
问题描述
我需要隔离 django 的默认(身份验证、内容类型、会话)应用程序数据库,我在文档 [Multiple Databses][1] 中阅读了所有内容都很清楚且解释清楚,但对我不起作用:(
设置.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/drouter.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/
解决方案
你忘了一个R。
DATABASE_ROUTES = ['core.dbrouter.AuthRoute', 'core.dbrouter.GisRoute']
↓
DATABASE_ROUTERS = ['core.dbrouter.AuthRoute', 'core.dbrouter.GisRoute']
推荐阅读
- r - 过滤/子集包含某些字符串以外的任何内容的行
- python - 我想在ldap中同时修改多个值。我怎样才能做到这一点?
- html - QR Code 字体样式是将每个字符呈现为 qr 代码而不是整个文本
- python - 拦截标头并即时修改
- chart.js - 有没有办法通过悬停突出显示折线图上的一条线?
- javascript - 如何计算 Javascript 上两个函数的结果?
- c++ - 如何在 Quick Bench 中开启多线程?
- node.js - 如何在 mineflayer 包 node.js 中拆分单词
- python - Selenium 在 ::before 之后不显示表格内容
- node.js - 如何在 node.js 应用程序中用命令行脚本替换 node-cron