Search code examples
pythondjangodatabasemaster-slave

Django test chooses database randomly


I have multiple database settings (master/slave) as follow:

DATABASES = {
    'default': dj_database_url.parse('postgres://localhost:5432/master_db'),
    'slave': dj_database_url.parse('postgres://localhost:5432/slave_db'),
}

Slave database is only used explicitly for some offline expensive query (with objects.using and is not used any of testcases. As noted in django docs 'default' database is used when there is no database specified explicitly. The problem is when I run python manage.py test --keepdb it sometimes run tests with slave database which raises error (because there is no table created in slave databse).

The output of python manage.py test --keepdb when it uses slave:

Using existing test database for alias 'slave'...
Traceback (most recent call last):
  File "/usr/local/lib/python3.6/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
psycopg2.ProgrammingError: relation "categorization_category" does not exist
LINE 1: ...rization_category"."last_modified_date" FROM "categoriz...

The output of when it uses default:

# some ..... and warnings showing tests are running
Creating test database for alias 'default'...
# some debug info in tests
Destroying test database for alias 'default'...
Ran 119 tests in 91.456s

OK

How can I force test to use only 'default' database as test database?


Solution

  • Add this to your settings:

    DATABASES['slave']['TEST'] = {
        'MIRROR': 'default',
    }
    

    Here you can read why.