首页 > 解决方案 > 尝试解析 Django 文件会引发异常

问题描述

我的目标是使用 package.json 解析my_app项目应用程序内的 Django 文件importlib。为了做到这一点,我有以下代码:

import ntpath

class Foo:

    def _get_module_name(self, path, remove_extension=True):
        head, tail = ntpath.split(path)
        if remove_extension:
            tail = tail.split('.')[0]
        return tail

    def my_method(self, path):
        module_name = self._get_module_name(path)
        module = importlib.machinery.SourceFileLoader(
            module_name, path).load_module() # Error arises
  

然后,我有一个管理命令可以调用my_method

from django.core.management import BaseCommand

class Command(BaseCommand):
    help = 'Generates string for models creation'

    def handle(self, *args, **kwargs):

foo = Foo()
foo.my_method('/my_app_full_path/models.py')

在注释的代码行上,我遇到错误说:

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

我已经明确地将 my_app 包含在 INSTALLED_APPS 中,它里面有一个init .py 文件。Django 项目本身运行正常,所有迁移都可以正确应用。问题仅存在于管理命令代码中。有什么提示吗?

UPD:对我来说,代码适用于serializers.py. 问题只出现在以下情况models.py

标签: djangopython-importlib

解决方案


推荐阅读