
本文详解 Django 项目中跨目录导入自定义 Python 模块时常见的 AttributeError 问题,重点说明 __init__.py 的正确配置方式,确保 from ... import * 或显式导入能正常暴露子模块(如 refresh.py)中的函数。
本文详解 django 项目中跨目录导入自定义 python 模块时常见的 `attributeerror` 问题,重点说明 `__init__.py` 的正确配置方式,确保 `from ... import *` 或显式导入能正常暴露子模块(如 `refresh.py`)中的函数。
在 Django 项目中,将业务逻辑(如数据刷新、配置加载)抽离到独立的 Python 包(如 python_code/object_refresh/)是良好实践。但当视图试图通过 from core_project.python_code.object_refresh import * 导入时,却报错 AttributeError: module '...object_refresh' has no attribute 'refresh'——这并非路径错误,而是 Python 包导入机制未被正确激活。
根本原因在于:*`import 仅导入包的init.py中显式声明的名称**,不会自动递归导入该目录下所有.py文件。即使refresh.py和config.py存在,若init.py` 未主动引入它们,外部就无法访问其内容。
✅ 正确做法:编辑 python_code/Object_refresh/__init__.py(注意文件名大小写需与实际一致),显式导入所需模块:
# python_code/Object_refresh/__init__.py from . import refresh from . import config # 可选:若需直接暴露 refresh() 函数,可进一步导入 # from .refresh import refresh
⚠️ 注意事项:
立即学习“Python免费学习笔记(深入)”;
- 确保
__init__.py文件存在且命名正确(含两个下划线,非__init.py__); - 使用相对导入(
.refresh)而非绝对路径,保证包内引用健壮性; - 若希望
from object_refresh import refresh直接可用,推荐在__init__.py中写from .refresh import refresh,而非仅import refresh(后者需通过object_refresh.refresh.refresh()调用); - 在 Django 视图中,推荐使用明确导入代替
import *,提升可读性与可维护性:
# 推荐写法(清晰、安全、易调试)
from core_project.python_code.Object_refresh import refresh, config
def run_refresh(request):
# ...
newfeature = asyncio.run(refresh.refresh(rows_to_refresh, schema, 'tbl_name'))
return JsonResponse({"result": newfeature})最后,请确认 Django 的 PYTHONPATH 已包含 core_project 根目录(通常 manage.py 启动时已自动处理),避免因模块路径不可见导致 ModuleNotFoundError。完成上述配置后,refresh 模块即可被正常识别与调用。


















