Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connect to a different database in django shell

How can I connect to a different database when in a Django shell?

Something like:

python manage.py shell --database=slave

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

This is what my settings 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,
    },
}
like image 536
Anshul Goyal Avatar asked Jul 12 '16 14:07

Anshul Goyal


2 Answers

You could select database in your query with using() ORM's method:

# This will hit a model in your default DB:
Model.objects.using('default').all()

# And this will hit a model in your slave DB:
Model.objects.using('slave').all()
like image 185
Gocht Avatar answered Sep 28 '22 02:09

Gocht


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,
    },
}

# OR
#
# DATABASES['master'] = DATABASES['default']
# DATABASES['default'] = DATABASES['slave']

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


Or, alternatively, just create a second settings module:

project/
    settings.py
    shell_settings.py

project/shell_settings.py would look like:

from .settings import *

DATABASES['master'] = DATABASES['default']
DATABASES['default'] = DATABASES['slave']

and run python manage.py shell --settings=project.shell_settings

like image 26
Antoine Pinsard Avatar answered Sep 28 '22 01:09

Antoine Pinsard