连接到 Django 测试数据库

Connect to Django test database

有没有办法使用 connections 连接到 django 测试数据库?

我试过了 cursor = connections['test_name_of_main_db'].cursor() 并在设置中指定了测试数据库名称,但我仍然收到错误:

Traceback (most recent call last):


File "/home/tets/4d/lib/python3.5/site-packages/django/db/utils.py", line 176, in ensure_defaults


  conn = self.databases[alias]
KeyError: 'auto_tests'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):



     File "/home/tets/healthware_server/component/medical/tests.py", line 72, in test_model_observation
cursor = connections['auto_tests'].cursor()
     File "/home/tets/4d/lib/python3.5/site-packages/django/db/utils.py", line 208, in __getitem__ self.ensure_defaults(alias)
     File "/home/tets/4d/lib/python3.5/site-packages/django/db/utils.py", line 178, in ensure_defaults
raise ConnectionDoesNotExist("The connection %s doesn't exist" % alias)

django.db.utils.ConnectionDoesNotExist: The connection auto_tests doesn't exist

根据 docs:

The default test database names are created by prepending test_ to the value of each NAME in DATABASES.

但在您的堆栈跟踪中,错误显示:

django.db.utils.ConnectionDoesNotExist: The connection auto_tests doesn't exist

您确定您使用的别名正确吗?根据错误,它正在寻找一个名为 auto_tests.

的数据库

作为另一个调试步骤,您可以在测试期间打印所有别名以查看哪些可用

for alias in connections:
    print(alias)

当然,您也可以尝试使用默认数据库,看看在测试期间是否适合您:

# note that it is 'connection' and not 'connections'
from django.db import connection
cursor = connection.cursor()