Django default db.sqlite3 if your custom database is not found

Let's say I have this really happy database that I am using with Django, but for debugging purposes I want to use the default `db.sqlite3 'database in the settings.py file if my database is glad not found or users are not able easy to set up a database.

How can I accomplish this task using Django?

+3


source to share


2 answers


The way I do it is this:

In settings.py:

import dj_database_url # you'll need this in requirements.txt

DATABASES = {
    "default": dj_database_url.config(default='sqlite:///db.sqlite3'),
}

      

If the DATABASE_URL environment variable is set, as it was during production (Heroku for me, but you can use the DATABASE_URL enb variable anywhere) then use it. Otherwise fall back to sqlite



Also, at the end of settings.py, I have:

# Import optional local settings.  This must be at the END of this file.
try:
    from .local import *
except ImportError:
    pass

      

So you can override the sqlite database in two ways: you can set the DATABASE_URL environment variable, or you can create a "local.py" file (exclude this from version control via .gitignore) that overrides it and others selectively. Why two paths? First of all, because most of the developers on my team are more comfortable managing the local settings file than environment variables.

I use this philosophy for all of my settings, which may differ between dev and production, or which contain something I don't want in source control for any other reason.

+2


source


You can, for example, set the database malfunction of your debug var. In the settings file:



if DEBUG:
//test database using sqlite
 DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'you_db_name.sqlite3'),
    }
 }
else:
   //here your prod database

      

+2


source







All Articles