Unable to migrate in Second Multi database in Django

18 views Asked by At

I have implemented multi-DB concept inside my Django project where for whole project i am using default db and for User I am using separate DB

here are the settings.py file configs:


DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': default_db,
        'USER': env('DB_USER'),
        'PASSWORD': env('DB_PASSWORD'),
        'HOST': env('DB_HOST'),
        'PORT': env('DB_PORT'),
    },
    'auth_db': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'user_auth_db',
        'USER': env('DB_USER'),
        'PASSWORD': env('DB_PASSWORD'),
        'HOST': env('DB_HOST'),
        'PORT': env('DB_PORT'),
    },

}

# ADDING ROUTE TO SPECIFY DB ROUTING SPECIFIC user RELATED CHANGES TO REFLECT Into auth_db database not inside default db

DATABASE_ROUTERS = ["main_Project_directory.db_routers.UserAuthRouter"]

Now this is the db_routers.py file

class UserAuthRouter:
    """
        A router to control all database operations on models in the
        auth and contenttypes applications.
    """
    route_app_labels = {"auth_user", 'contenttypes'}  # Apps to be include inside auth_db

    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 "auth_db"
        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 "auth_db"
        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

        # Allow relations if one of the objects is from 'auth_user' and the other is not
        if "auth_user" in [obj1._meta.app_label, obj2._meta.app_label]:
            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 == "auth_db"
        return None

I am trying to make changes inside my User model which is inside my auth_user application and trying to migrate it is not reflecting changes inside new DB But If I do write Operation it is storing the data inside my new db which is separated for User model.

I want to migrate changes inside new DB.

0

There are 0 answers