mu 無 mu 無 - 4 months ago 14
Python Question

Connect to a different database in django shell

How can I connect to a different database in django shell?

Some thing like,

python manage.py shell --database=slave


I tried googling all around, but couldn't find anything useful on this.

This is what my settigns looks like:

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'db1',
'USER': 'user',
'PASSWORD': 'password',
'HOST': '10.10.10.10',
'PORT': '',
'CONN_MAX_AGE': 1000,
},
'slave':{
'ENGINE': 'django.db.backends.mysql',
'NAME': 'db2',
'USER': 'user',
'PASSWORD': 'password',
'HOST': '10.10.10.10',
'PORT': '',
'CONN_MAX_AGE': 1000,
},
}

Answer

You can split your settings module into submodules. For instance:

project/
    settings/
        __init__.py
        base.py
        dev.py
        prod.py
        shell.py

Your main/common settings are located in project/settings/base.py

In development, set DJANGO_SETTINGS_MODULE environment variable to project.settings.dev.

project/settings/dev.py may look like:

from .base import *

DEBUG = True

project/settings/shell.py may look like:

from .dev import *

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'db2',
        'USER': 'user',
        'PASSWORD': 'password',
        'HOST': '10.10.10.10',
        'PORT': '',
        'CONN_MAX_AGE': 1000,
    },
}

Then run python manage.py shell --settings=project.settings.shell.