【问题标题】:Django "Model class <Class> doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS" after splitting models拆分模型后,Django“模型类 <Class> 未声明显式 app_label 并且不在 INSTALLED_APPS 中的应用程序中”
【发布时间】:2021-10-09 02:22:00
【问题描述】:

我遇到了这个错误,我已经尝试修复它好几个小时了,一旦我将我的 models.py 分离到一个包含多个文件的目录中,它就出现了。

这是我项目的当前结构。我省略了很多文件,但这些是相关的:

  • 项目文件夹
    • 学院
      • app1
      • 应用程序2
        • manage.py
        • 型号
          • _ _ 初始化 _ _.py
          • content.py
          • session.py
      • app3
    • 配置
    • 静态

以前,我将所有模型放在 app2 内的一个文件中,名为 models.py。然而,随着文件开始变得太大,我将每个模型分成不同的类别。另外,我在__init__.py 中导入了这些元素:

from academy.app2.models.content import *
from academy.app2.models.session import *

现在,当我像往常一样尝试使用 python manage.py makemigrations app2 进行迁移时,我收到了这个错误:

RuntimeError: Model class app2.models.content.Reward doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.

当我搜索这个错误时,我遇到了this answer,但是,当我添加声明 app_label 的元类时,我得到了这个错误:

RuntimeError: Conflicting 'reward' models in application 'app2': <class 'academy.app2.models.content.Reward'> and <class 'app2.models.content.Reward'>.

这是我的 app2 配置文件:

class App2Config(AppConfig):
    name = 'academy.app2'

这是我的 INSTALLED_APPS:

INSTALLED_APPS = [
    ...
    'academy.app2.apps.App2Config',
    ...
]

当我有一个单独的 models.py 文件时没有发生此错误,但是当我将它分成单独的文件时。我还尝试创建一个额外的基本模型,并在该模型中定义元类,继承其余模型,但没有成功。

【问题讨论】:

  • INSTALLED_APPS 中的CoreConfig 更改为App2Config 是否有效? AppConfig 班级的实际位置。
  • @Abhyudai 对不起。这是一个错字。现在已经修复了

标签: python django


【解决方案1】:

经过多次尝试,我找到了解决问题的方法:

首先,我将__init.py__ 编辑为以下语法:

from .content import *
from .session import *
from .system import *

此外,我将导入从一个文件更新到另一个文件,从 app2.models.file 格式更新为:academy.app2.models.file

没有必要添加基类。我现在能够正确运行迁移。我希望这对某人有所帮助。

【讨论】:

    猜你喜欢
    • 2018-01-03
    • 1970-01-01
    • 2023-02-18
    • 2021-10-23
    • 1970-01-01
    • 2020-08-13
    • 2018-10-19
    • 2018-12-29
    • 2019-08-28
    相关资源
    最近更新 更多