首页 > 解决方案 > 如何在 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/

标签: pythondjango

解决方案


你忘了一个R。

DATABASE_ROUTES = ['core.dbrouter.AuthRoute', 'core.dbrouter.GisRoute']
              ↓
DATABASE_ROUTERS = ['core.dbrouter.AuthRoute', 'core.dbrouter.GisRoute']

推荐阅读