How to automatically switch debug/production database in settings.py in Django
Since settings.py is just an ordinary Python file we can use simple `if else` block.
Published: July 25, 2020 Sponsored App StoreI apologize if the following is just plain obvious but for some reason I discovered it just now even though I first touched Django a couple of years back. If you have single settings.py
file then there is an easy way to automatically correctly use debug and production databases and be those different ones.
In the past I would either have specific settings files for local and production environment but for new projects or small ones this may seem like over-engineering. So in this case I would just resort to commenting out the database I did not want in the moment.
And then I had a sort of epiphany. Because settings.py
is not magical. It is just a Python file with bunch of configuration values. I have already utilized this for example to separate Django's, mine and 3rd party apps and join these lists together for the INSTALLED_APPS
settings.
And well you can use if
statements here too! So the simple solution to have both debug and production databases available without any manual switching you can just ask if DEBUG
is True
:
if DEBUG:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'debug.sqlite3'),
}
}
else:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'production.sqlite3'),
}
}
I am using example with SQLite but of course this will work for any database and also any condition.
Maybe I am not the only one in the world who did not discover this when they first started with Django and hopefully it will help someone.