VS Code中django-simple-history导入错误:Pylance无法解析'simple_history.models'
问题描述
开发Django项目时,尝试用django-simple-history追踪模型变更,导入simple_history.models中的HistoricalRecords时,VS Code的Pylance提示错误:Import 'simple_history.models' could not be resolved。
已完成的排查步骤
- 激活项目虚拟环境,通过
pip freeze确认已安装django-simple-history==3.5.0 - 用
pip show django-simple-history验证包的安装路径和信息正确 - 删除并重建虚拟环境,问题未解决
- 检查
venv\Lib\site-packages\simple_history目录,确认HistoricalRecords模型文件存在
修复方案
1. 确认VS Code使用的Python解释器
按Ctrl+Shift+P(Windows/Linux)或Cmd+Shift+P(Mac)打开命令面板,输入Python: Select Interpreter,选择当前项目虚拟环境的Python解释器(比如./venv/Scripts/python.exe)。VS Code偶尔会默认使用全局Python,导致无法识别虚拟环境内的包。
2. 重启Pylance语言服务
打开命令面板,输入Python: Restart Language Server,重启Pylance让它重新扫描虚拟环境的包目录,很多时候缓存问题会导致这类识别错误。
3. 检查导入语句的正确性
注意django-simple-history的正确导入是复数形式:
from simple_history.models import HistoricalRecords
如果写成单数HistoricalRecord,不仅Pylance会报错,项目运行时也会抛出导入异常。
4. 配置INSTALLED_APPS
确保在项目的settings.py中已经添加simple_history到INSTALLED_APPS:
INSTALLED_APPS = [ # 其他已配置应用 'simple_history', ]
虽然这不会直接引发导入错误,但配置缺失可能影响Pylance对包的识别逻辑。
5. 手动添加包路径到VS Code配置
打开项目的.vscode/settings.json,添加虚拟环境的site-packages路径到分析路径:
{ "python.analysis.extraPaths": [ "./venv/Lib/site-packages" ] }
保存后重启VS Code,让Pylance强制扫描该目录。
6. 强制重新安装包
如果以上方法都无效,尝试强制重新安装指定版本的包:
pip install django-simple-history==3.5.0 --force-reinstall
安装完成后再次验证导入是否正常。
内容的提问来源于stack exchange,提问作者Mahyah Binti Idris

