I have django application which has two database defaultdb
and externdb
JavaScript
x
31
31
1
DATABASES = {
2
'default': {
3
'ENGINE': 'django.db.backends.mysql',
4
"NAME": config("DB_NAME"),
5
"USER": config("DB_USER"),
6
"PASSWORD": config("DB_PASSWORD"),
7
"HOST": config("DB_HOST"),
8
"PORT": config("DB_PORT"),
9
'OPTIONS': {
10
'charset': 'utf8mb4',
11
'init_command': "SET sql_mode='STRICT_TRANS_TABLES'"
12
},
13
'TEST': {
14
'NAME': 'test_{0}'.format(config("DB_NAME")),
15
'MIRROR': "default",
16
},
17
},
18
'extern': {
19
'ENGINE': 'django.db.backends.mysql',
20
'NAME': config("DB_EXTERN_NAME"),
21
'USER': config("DB_EXTERN_USER"),
22
'PASSWORD': config("DB_EXTERN_PASSWORD"),
23
'HOST': config("DB_EXTERN_HOST"),
24
'PORT': config("DB_EXTERN_PORT"),
25
'TEST': {
26
'NAME': 'test_{0}'.format(config("DB_EXTERN_NAME")),
27
'MIRROR': "extern",
28
},
29
}
30
}
31
The application works well but when testing ,this error occurs below
when trying to access the extern database
JavaScript
1
6
1
from extern_db.models import TBasicInfo
2
3
class HelpViewTest(TestCase):
4
def test_api(self):
5
tb = TBasicInfo.objects.get(info_id=10352)
6
This error occurs
JavaScript
1
2
1
AssertionError: Database queries to 'extern' are not allowed in this test. Add 'extern' to defapp.tests.HelpViewTest.databases to ensure proper test isolation and silence this failure.
2
which setting should I check??
Advertisement
Answer
Change:
JavaScript
1
2
1
tb = TBasicInfo.objects.get(info_id=10352)
2
to this:
JavaScript
1
2
1
tb = TBasicInfo.objects.using("extern").get(info_id=10352)
2
OR
You can also add databases = “extern” to this:
JavaScript
1
6
1
from extern_db.models import TBasicInfo
2
3
class HelpViewTest(TestCase):
4
def test_api(self):
5
tb = TBasicInfo.objects.get(info_id=10352)
6
final version:
JavaScript
1
8
1
from extern_db.models import TBasicInfo
2
3
class HelpViewTest(TestCase):
4
databases = 'extern'
5
6
def test_api(self):
7
tb = TBasicInfo.objects.get(info_id=10352)
8
This method is what it basically suggests you to do in that message.