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

执行Django测试时触发MySQLdb.ProgrammingError(1146)表不存在错误

Django测试时MySQL表不存在问题解决

问题

执行python manage.py test运行测试时触发错误:

MySQLdb.ProgrammingError: (1146, "Table 'test_sageservice.processed_transactions' doesn't exist")

已执行python manage.py makemigrations和python manage.py migrate,过程无异常,但测试仍报错。

涉及代码

tests.py

from django.test import TestCase

class DashboardTests(TestCase):
    def test_uses_dashboard_template(self):
        response = self.client.get('/')
        self.assertTemplateUsed(response, 'dashboard.html')

settings.py 数据库配置

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'sageservice',
        'USER': 'root',
        'PASSWORD': 'not_my_password',
        'HOST': '127.0.0.1',
        'PORT': '3306',
   }
}

排查与解决步骤

  • 检查模型与迁移文件:
    确认processed_transactions对应的模型存在,且已生成迁移文件。运行python manage.py showmigrations查看该模型所属app的迁移是否已全部应用。如果没有迁移文件,执行python manage.py makemigrations <目标app名称>手动生成。
  • 重建测试数据库:
    Django测试会自动创建前缀为test_的数据库(此处为test_sageservice),但迁移可能未正确同步到测试库。手动删除测试库后重新运行测试即可:
    1. 登录MySQL执行:DROP DATABASE test_sageservice;
    2. 重新运行测试:python manage.py test,Django会自动重建测试库并应用所有迁移。
  • 检查模型配置与路由:
    确认processed_transactions模型的Meta类未错误指定数据库,或不存在自定义数据库路由导致测试库无法同步该表。
  • 第三方app检查:
    如果processed_transactions来自第三方app,确认该app已在INSTALLED_APPS中注册,且其迁移已正确应用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 05:22:15