django - 尝试解析 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
解决方案
推荐阅读
- emacs - 如何在使用 Org-Babel 进行评估时将一个代码块作为序言添加到另一个代码块,以实现代码块的 noweb 样式扩展?
- clojure - 使用 Clojure Spec 检查缺点的类型一致性?
- angular - Angular 6 - 动态填充表格内容值
- java - 正则表达式中的匹配组
- c++ - 为什么我不能在这样的字符串上替换字符?
- node.js - Firebase 检查数据库是否存在
- c++ - 使用 CXXFLAGS 在我的 makefile 中启用 C++ 11 支持
- java - 请求位置更新返回相同的坐标
- java - 如何做文件夹和文件的递归树?
- python - Flask Admin Ckeditor 图片上传