我有一个django Web应用程序,它使用两个数据库:MySQL和PostgreSQL。我想运行一些单元测试,检查对象创建并为PostgreSQL数据库中的模型读取它们。当我运行它们时,没有使用以下错误创建测试数据库:
django.db.utils.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'jsonb NULL, `processed_payload` jsonb NULL, `scheduled_time` datetime(6) NULL, `' at line 1")
我的settings.py文件包含如下所示的数据库条目(放置别名而不是实际值):
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'name_1',
'USER': 'user_1',
'PASSWORD': 'user_pwd_1',
'HOST': 'host_1',
'PORT': '3306',
},
'payouts': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'name_2',
'USER': 'user_2',
'PASSWORD': 'user_pwd_2',
'HOST': 'host_2',
'PORT': '5432',
}
如何确保为PostgreSQL而不是MySQL创建数据库,以便创建表查询不会失败?
编辑: 包括我创建的APIRouter,用于在运行应用程序时管理数据库选择。
class APIrouter(object):
payouts_tables = ['PayoutsConfig', 'PayoutStructures']
def db_for_read(self, model, **hints):
if model.__name__ in self.payouts_tables:
return 'payouts'
else:
return None
def db_for_write(self, model, **hints):
if model.__name__ in self.payouts_tables:
return 'payouts'
return None
def allow_syncdb(self, db, model):
if model.__name__ in self.payouts_tables:
return True
return None
def allow_migrate(self, db, app_label, model_name=None, **hints):
if app_label == 'payouts':
return db == 'payouts'
return None
还包括我尝试运行的单元测试代码段:
class PayoutsTestCase(TestCase):
def setUp(self):
conf = {"key": "value"}
config = PayoutsConfig.objects.create(config_name="unit_test_config_1",payout_type=1,payout_config=conf)
structure = PayoutStructures.objects.create(structure_name="unit_test_1", payout_configurations=[config])
def test_structure_name(self):
structure = PayoutsConfig.objects.get(structure_name="unit_test_1")
self.assertEqual(structure.name, "unit_test_1")
本次测试中使用的模型如下:
class PayoutsConfig(models.Model):
config_name = models.CharField(max_length=100,null=True)
payout_type = models.IntegerField(choices=PayoutTypes.payout_type_choices,null=True)
payout_config = JSONField(null=True)
class PayoutStructures(models.Model):
structure_name = models.CharField(max_length=100,null=True)
payout_configurations = models.ManyToManyField('PayoutsConfig', related_name='structures')