How to Migrate only required models table if using Multiple DB in django

Viewed 230

I have tried migrating models when using Multiple DB in django. It is creating all table in both the DB by default, Can we customize it so unnecessary table can't be made in the other DB.

I am using this right now for migration.

def allow_migrate(self, db, app_label, model_name=None, **hints):
    # checking if model hasattr() to migrate in which db
    if hints:
        if hasattr(hints['model'],'use_db'):
            return db == getattr(hints['model'],'use_db')
    return None
1 Answers

Make a router directory in root folder. Create router.py file in it, lets assume you have two database configured in settings.py , one named 'primary' and another 'secondary'

Now route the migration in such way that it will only allow migration on specific apps listed. Now each database will contain model of allowed apps only.

class Secondary:
    route_app_labels = ['categories','products']
    def allow_migrate(self, db, app_label, model_name=None, **hints):
        if app_label in self.route_app_labels:
            return db == 'secondary'
        return None

class Primary:
    route_app_labels = ['account',
                    'admin',
                    'auth',
                    'authtoken',
                    'contenttypes'] 
    def allow_migrate(self, db, app_label, model_name=None, **hints):
        if app_label in self.route_app_labels:
            return db == 'primary'
        return None

Database and routes in settings.py file:

DATABASES = {
    'primary': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': config('POSTGRES_DB_NAME'),
        'USER': config('POSTGRES_DB_USER'),
        'PASSWORD': config('POSTGRES_DB_PASSWORD'),
        'HOST': config('POSTGRES_DB_HOST'),
        'PORT': config('POSTGRES_DB_PORT'),
        'TEST': {
            'DEPENDENCIES': [],
        },
    },
    'secondary': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': config('MYSQL_DB_NAME'),
        'USER': config('MYSQL_DB_USER'),
        'PASSWORD': config('MYSQL_DB_PASSWORD'),
        'HOST': config('MYSQL_DB_HOST'),
        'PORT': config('MYSQL_DB_PORT'),
        'TEST': {
            'DEPENDENCIES': ['primary'],
        },
    }

DATABASE_ROUTERS = ['routers.router.Primary', 'routers.router.Secondary', ]

Note: Make sure previous migrations are cleared/deleted else previous migrations will create the tables.

Related