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

如何在Django项目中配置__init__.py实现models目录下模型类自动导入

Django models目录自动导入模型类方案

将以下代码直接写入cbapp/models/__init__.py即可实现新增模型文件自动导入,无需手动修改导入语句:

import os
import importlib
from django.db import models

# 遍历当前目录下的所有Python文件
for file_name in os.listdir(os.path.dirname(__file__)):
    # 过滤非Python文件和__init__.py本身
    if not file_name.endswith(".py") or file_name == "__init__.py":
        continue
    # 提取模块名
    module_name = file_name[:-3]
    # 动态导入模块
    current_module = importlib.import_module(f".{module_name}", package=__name__)
    # 筛选模块内定义的Django模型类
    for attr_name in dir(current_module):
        attr = getattr(current_module, attr_name)
        if (
            isinstance(attr, type)
            and issubclass(attr, models.Model)
            and attr.__module__ == current_module.__name__
        ):
            # 将模型类注册到当前模块的全局命名空间
            globals()[attr_name] = attr

# 可选:配置__all__支持通配符导入(如 from cbapp.models import *)
__all__ = [
    k for k, v in globals().items() 
    if isinstance(v, type) and issubclass(v, models.Model)
]

功能说明

  • 新增模型文件后不需要调整__init__.py代码,只要按原有规范在独立py文件中定义模型类即可自动识别
  • 自动过滤当前模块内导入的其他类/函数,仅保留当前文件定义的Django模型类
  • 完全兼容Django的模型检测逻辑,makemigrations、migrate等核心命令可正常识别所有模型

注意事项

  • 保持现有命名规范即可:模型文件用蛇形命名(如user_preferences.py),模型类用大驼峰命名(如UserPreferences)
  • 单个模型文件中如果定义了多个Django模型类,也会被全部自动导入

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 08:06:04