Django runserver custom database

A cleaner and more scalable way to switch configurations than to create several config files would be to use environment variables (see #3 of the twelve-factor app methodology used by Heroku and others). For example:

from os import environ

DATABASES = {
    'main': {
        'NAME': 'db.db',
        'ENGINE': 'django.db.backends.sqlite3'
    },
    'tests': {
        'NAME': 'tests.db',
        'ENGINE': 'django.db.backends.sqlite3'
    },
}

default_database = environ.get('DJANGO_DATABASE', 'main')
DATABASES['default'] = DATABASES[default_database]

You can then change the default database by setting the DJANGO_DATABASE environment variable.

export DJANGO_DATABASE='tests'
./manage.py runserver

...or...

DJANGO_DATABASE='tests' ./manage.py runserver

You could also set environment variables using Python code.


Edit: To make this process easier, Kenneth Reitz has written a nice little app called dj-database-url.


I discovered that the right command to call in Django 1.4 is:

django-admin.py runserver --settings=myproject.settings_tests

Where is this information in the Django DOCS?

Thanks for all your response

Griffosx


Create settings_tests.py with following:

from settings import *

DATABASES = {
    'default': {
        'NAME': 'tests.db',
        'ENGINE': 'django.db.backends.sqlite3'
    },

}

Execute django-admin.py runserver --settings=settings_tests

Tags:

Django