python - 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。
在尝试了这个并进行了迁移之后,错误仍然是一样的。
解决方案
我想简单的解决方案 - 几乎是空的 django 项目。这是使您可以从 python https://github.com/askaliuk/django-orm-standalone访问 django ORM 的旧项目,但我不确定它是否有效。
推荐阅读
- php - 奇怪的解析错误:语法错误,意外`'if' (T_IF) ERROR`
- php - php合并两个动态数组递归
- angular - 将 [pageSize] 属性添加到 Kendo 网格后的 ExpressionChangedAfterItHasBeenCheckedError
- regex - 使用 Hive / Spark SQL 在 URL 中匹配字符串
- ibm-domino - 如何处理收件人地址中的空间
- command-line-interface - windows10 1903安装成功后如何运行lb/lb4 loopback cli 3 or 4 command not found
- abap - ALV 网格中的多行标题
- r - 在 R 中的 Shiny 应用程序中声明变量
- linux - 如何设置特定用户可以在redhat中运行某些root命令
- ruby-on-rails - 使用国际化时如何渲染正确的视图