You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django应用可正常访问数据库模型,Pytest测试提示无效对象名

解决方案

1. 修正模型Meta类的表名与schema配置

SQL Server依赖schema定位表,你的模型需要明确指定包含schema的完整表名(若为现有表还需关闭Django的表管理):

class StudentsWithHolds(models.Model):
    person_id_number = models.CharField(max_length=50)
    hold_type_code = models.CharField(max_length=50)

    class Meta:
        db_table = 'dbo.Students_with_Holds'  # 明确指定schema+表名
        managed = False  # 若表为数据库中已存在的非迁移创建表,必须添加此选项
        app_label = 'your_app_name'  # 替换为模型所在的app名称

2. 配置数据库连接的默认schema

在settings.py的DATABASES配置中,为Coursematch数据库添加默认schema选项,确保Django自动使用dbo:

DATABASES = {
    'Coursematch': {
        'ENGINE': 'mssql',
        'NAME': 'Coursematch',
        'USER': 'your_username',
        'PASSWORD': 'your_password',
        'HOST': 'your_db_host',
        'PORT': '1433',
        'OPTIONS': {
            'driver': 'ODBC Driver 17 for SQL Server',
            'schema': 'dbo',  # 设置默认schema为dbo
        },
    }
}

3. 验证Django生成的SQL语句

在测试中打印模型生成的SQL,确认是否包含正确的schema和表名:

@pytest.mark.django_db(databases=['Coursematch'])
def test_db_access(self):
    # 打印生成的SQL,检查表名格式
    print(StudentsWithHolds.objects.using('Coursematch').all().query)
    testobj = StudentsWithHolds.objects.using('Coursematch').create(
        person_id_number='testPIDnum',
        hold_type_code='test'
    )
    assert testobj.person_id_number == 'testPIDnum'

若输出SQL中表名无dbo前缀,说明schema配置未生效,需回到前两步调整。

4. 调整测试类的数据库上下文

如果测试是类方法(使用self),若继承Django的TestCase,需明确指定使用的数据库,且无需额外添加@pytest.mark.django_db标记:

from django.test import TestCase

class TestDBOperations(TestCase):
    databases = ['Coursematch']  # 指定测试使用的数据库

    def test_db_access(self):
        testobj = StudentsWithHolds.objects.create(
            person_id_number='testPIDnum',
            hold_type_code='test'
        )
        assert testobj.person_id_number == 'testPIDnum'

5. 确认迁移与数据库同步

若表由Django迁移创建,重新执行迁移并验证表存在:

python manage.py makemigrations
python manage.py migrate --database=Coursematch

执行后检查数据库中是否存在Coursematch.dbo.Students_with_Holds表,确保迁移生成的表名与实际一致。


内容的提问来源于stack exchange,提问作者Enderhippo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 16:30:06