Parthapratim Neog
Parthapratim Neog

Reputation: 4478

How to use inspectdb for multiple mysql schemas in django?

This is the DATABASES dictionary in my Settings.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'account',
        'USER': 'xxxx',
        'PASSWORD': 'xxxx',
        'HOST': 'localhost',
        'PORT': '3306'
    }
}

My database has multiple schemas, for example, account, login, notifications etc. When I do a python manage.py inspectdb, I only get the classes for the tables in the "account" schema, but I want the classes for all the schemas. I tried doing python manage.py inspectdb --database=login, but I get a django.db.utils.ConnectionDoesNotExist exception

But, if I change the settings to

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'account',
        'USER': 'xxxx',
        'PASSWORD': 'xxxx',
        'HOST': 'localhost',
        'PORT': '3306'
    },
    'login': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'login',
        'USER': 'xxxx',
        'PASSWORD': 'xxxx',
        'HOST': 'localhost',
        'PORT': '3306'
    },
}

I get the proper classes of the table login on executing python manage.py inspectdb --database=login. But, problem is, if this is supposed to be the procedure, I have to make an option in the DATABASES option, which will become really long, as I have more than 15 schemas, and I am not sure if doing that will be a good thing or not.

So, I want to know what is the right way of doing this.

I am on Django 1.10.5.

Upvotes: 0

Views: 2402

Answers (1)

aumo
aumo

Reputation: 5554

Django needs to know how to reach each one of your databases so you won't be able to avoid declaring them in the DATABASES setting. If your only concern is that you will loose readability, you may create a helper function to get rid of repetition.

For example:

def local_db(name):
    return {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': name,
        'USER': 'xxxx',
        'PASSWORD': 'xxxx',
        'HOST': 'localhost',
        'PORT': '3306',
    }

DATABASES = {
    'default': local_db('account'),
    'login': local_db('login'),
    # Etc.
}

If you want to inspect all databases at once, you may create a custom command to do so.

For example:

from django.conf import settings
from django.core.management.commands.inspectdb import Command as BaseCommand


class Command(BaseCommand):
    def handle(self, **options):
        for db_name in settings.DATABASES:
            options['database'] = db_name
            self.stdout.write('# Generated while inspecting database %s\n' % db_name)
            super().handle(**options)

Upvotes: 1

Related Questions