我有一个外部脚本,想要访问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
当我尝试运行脚本时,出现以下错误:
(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.
根据this question找到的一项建议是将网站添加到已安装的应用程序和site_id。
尝试了此步骤并进行了迁移后,错误仍然相同。
答案 0 :(得分:0)
我想简单的解决方案-几乎是空的django项目。这是旧项目,可让您从python https://github.com/askaliuk/django-orm-standalone访问django ORM,但我不确定它是否有效。