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,
},
}
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()
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With