[Python] How can I work with multiple databases in Django using database routers?

Discussão em 'Python' iniciado por Stack, Agosto 27, 2025.

  1. Stack

    Stack Membro Participativo

    I need to isolate Django's default (admin, auth, contenttypes, sessions) apps database. The documentation's Multiple databases example is not working.

    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 shows:

    Operations to perform:
    Apply all migrations: admin, auth, contenttypes, sessions
    Running migrations:
    No migrations to apply.


    Why?

    Continue reading...

Compartilhe esta Página