Skip to content

Instantly share code, notes, and snippets.

@gipi
Created October 31, 2011 08:54
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save gipi/1327143 to your computer and use it in GitHub Desktop.
Save gipi/1327143 to your computer and use it in GitHub Desktop.
Configure a Django project to use a specific database to use when run tests if we can't create databases with the user credential defined in the 'default' one
# Since we need a syncdb on all the databases, before the tests can be
# runned successfully we need to execute
#
# $ python manage.py syncdb
# $ python manage.py syncdb --database=test
#
# otherwise will be errors like
#
# 'django.db.utils.DatabaseError: no such table: django_site'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'bla',
'USER': 'foo'
'PASSWORD': 'bar'
},
'test': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'only4test.sqlite'
},
}
# http://stackoverflow.com/questions/4650509/different-db-for-testing-in-django
import sys
if 'test' in sys.argv:
DATABASES['default'] = DATABASES['test'];
@GrazingScientist
Copy link

Since this came up on my Google search quite high, you should be aware that in Django 3+ you can configure your database like this:

DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.postgresql_psycopg2',
            'NAME': 'bla',
            'USER': 'foo'
            'PASSWORD': 'bar'
            'TEST': {
                'MIRROR': 'test'
            }
        },
        'test': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': 'only4test.sqlite'
        },
}

See the MIRROR description and the Django Advanced Test documentation for details.

@gipi
Copy link
Author

gipi commented Mar 4, 2022

thanks @GrazingScientist for the comment, to be fair I forgot this gist existed :P

@GrazingScientist
Copy link

thanks @GrazingScientist for the comment, to be fair I forgot this gist existed :P

I thought so - after 11 years. ;)

@JANDSOL
Copy link

JANDSOL commented Jan 19, 2023

Thanks, all this time I was ignoring the last line of code, very sad to have wasted time on such small things...

@MukundBhatia
Copy link

MukundBhatia commented Feb 22, 2023

i think in last line this should be the code DATABASES['test'] = DATABASES['default']
I am actually trying to give a replica of my db as testing db so i can test my api and database without configuring multiple foriegn keys and appending data accordingly just for test of a put api

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment