Different db for testing in Django? Different db for testing in Django? django django

Different db for testing in Django?


In your settings.py (or local_settings.py):

import sysif 'test' in sys.argv:    DATABASES['default'] = {        'ENGINE': 'django.db.backends.sqlite3',        'NAME': 'mydatabase'    }


The way I handle this is through having multiple settings files, since I use that to maintain a set of common settings with modifications for each instance. It's a little more complicated to set up than some of the other solutions, but I needed to do it anyway because I was managing slightly different settings for local development, remote development, staging and production.

https://code.djangoproject.com/wiki/SplitSettings has a number of options for managing settings, and I've chosen a practice similar to the one described at https://code.djangoproject.com/wiki/SplitSettings#SimplePackageOrganizationforEnvironments

So, in my Django project directory, I have a settings folder that looks like this:

$ tree settingssettings├── defaults.py├── dev.py├── dev.pyc├── __init__.py├── lettuce.py├── travis.py├── unittest.py

The common settings are in settings/defaults.py and I import these in my instance settings files. So settings/unittest.py looks like this:

from defaults import *DATABASES = {    'default': {        'ENGINE': 'django.db.backends.sqlite3',        'NAME': 'my_database',    }} 

Then, when I want to run tests, I just execute:

$ ./manage.py test --settings=settings.unittest

to use sqlite for testing. I'll use a different settings module if I want to use a different test runner or database configuration.


You can specify test database in settings.py. Seehttps://docs.djangoproject.com/en/3.0/topics/testing/overview/#the-test-database

DATABASES = {    'default': {        'ENGINE': 'django.db.backends.postgresql',        'USER': 'mydatabaseuser',        'NAME': 'mydatabase',        'TEST': {            'NAME': 'mytestdatabase',        },    },}