Python Django测试随机选择数据库
我有多个数据库设置(主/从),如下所示:Python Django测试随机选择数据库,python,django,database,master-slave,Python,Django,Database,Master Slave,我有多个数据库设置(主/从),如下所示: DATABASES = { 'default': dj_database_url.parse('postgres://localhost:5432/master_db'), 'slave': dj_database_url.parse('postgres://localhost:5432/slave_db'), } 从属数据库仅显式地用于某些脱机昂贵查询(使用对象)。使用,不使用任何测试用例。 如“默认”中所述,当没有明确指定数据库时,
DATABASES = {
'default': dj_database_url.parse('postgres://localhost:5432/master_db'),
'slave': dj_database_url.parse('postgres://localhost:5432/slave_db'),
}
从属数据库仅显式地用于某些脱机昂贵查询(使用对象)。使用,不使用任何测试用例。
如“默认”中所述,当没有明确指定数据库时,将使用“默认”数据库。
问题是当我运行python manage.py test时——keepdb
有时会使用slave
数据库运行测试,这会引发错误(因为在slave
数据库中没有创建表)
python manage.py test的输出--keepdb
当它使用从机时:
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...
使用默认值时的输出:
# 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
如何强制测试仅使用“默认”数据库作为测试数据库?将此添加到您的设置中:
DATABASES['slave']['TEST'] = {
'MIRROR': 'default',
}
您可以阅读原因。它只将从属数据库重定向到主数据库,但为什么不使用“默认”数据库进行测试?