首页 > 解决方案 > django 使用来自外部脚本的模型

问题描述

我有一个外部脚本,我想访问 django 的模型,主要是因为它是套接字的外部实现,这很简单,我想看看这是否可行。

这是我根据 stackoverflow 上的答案在 settings.py 文件下方添加的代码片段。

#Allow Django to be used externally
from django.conf import settings
settings.configure(
    DATABASES={
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
        },
    },
    #TIME_ZONE='America/Montreal',
)

在我名为的单独脚本的开头,我path.py做了以下导入

import django

import pixelart.settings

os.environ.setdefault(
    "DJANGO_SETTINGS_MODULE",
    "pixelart.settings"
)
django.setup()

from gallery.models import ThumbnailCache, Area, Color

注意:我的 django 项目名为 pixelart,其中包含我从中导入模型的模型库。

当我尝试运行脚本时,出现以下错误:

(pixelart) sam@sam-Lenovo-G51-35:~/code/pixelart$ python path.py
Traceback (most recent call last):
File "path.py", line 23, in <module>
    from gallery.models import ThumbnailCache, Area, Color
File "/home/sam/code/pixelart/gallery/models.py", line 2, in <module>
    from django.contrib.auth.models import User
File "/home/sam/code/envs/pixelart/lib/python3.6/site-packages/django/contrib/auth/models.py", line 3, in <module>
    from django.contrib.contenttypes.models import ContentType
File "/home/sam/code/envs/pixelart/lib/python3.6/site-packages/django/contrib/contenttypes/models.py", line 134, in <module>
    class ContentType(models.Model):
File "/home/sam/code/envs/pixelart/lib/python3.6/site-packages/django/db/models/base.py", line 95, in __new__
    "INSTALLED_APPS." % (module, name)
RuntimeError: Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.

我根据这个问题找到的一个建议是将站点添加到已安装的应用程序和 site_id。

在尝试了这个并进行了迁移之后,错误仍然是一样的。

标签: pythondjango

解决方案


我想简单的解决方案 - 几乎是空的 django 项目。这是使您可以从 python https://github.com/askaliuk/django-orm-standalone访问 django ORM 的旧项目,但我不确定它是否有效。


推荐阅读