python - Django 独立脚本

标签 python django

我正在尝试从另一个 python 脚本访问我的 Django (v1.10) 应用程序数据库,但在这样做时遇到了一些问题。

这是我的文件和文件夹结构:

store
 store
   __init.py__
   settings.py
   urls.py
   wsgi.py
 store_app
   __init.py__
   admin.py
   apps.py
   models.py
   ...
 db.sqlite3
 manage.py

other_script.py

根据 Django's documentations我的 other_script.py 看起来像这样:

import django
from django.conf import settings

settings.configure(DEBUG=True)
django.setup()

from store.store_app.models import MyModel

但它会产生运行时错误:

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

我应该注意到我的 INSTALLED_APPS 列表包含 store_app 作为它的最后一个元素。

如果我尝试传递这样的配置:

import django
from django.conf import settings
from store.store_app.apps import StoreAppConfig

settings.configure(StoreAppConfig, DEBUG=True)
django.setup()

from store.store_app.models import MyModel

我明白了:

AttributeError: type object 'StoreAppConfig has no attribute  'LOGGING_CONFIG'.

如果我编辑 settings.py 并添加 LOGGING_CONFIG=None 我会收到另一个关于另一个缺失属性的错误,等等。

任何建议将不胜感激。

最佳答案

试试这个

import sys, os, django
sys.path.append("/path/to/store") #here store is root folder(means parent).
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "store.settings")
django.setup()

from store_app.models import MyModel

您可以在系统中的任何位置使用此脚本。

关于python - Django 独立脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39723310/

相关文章:

python - 在Python中解析XML

Python rpi GPIO输出控制基于GPIO输入和一天中的时间

python - 转换为字符串不产生所需的值

python - 将列表拆分为较小的等值列表

python - 将值插入数据库需要太长时间

python - 配置 django 设置以使用 1.4.1。加载模板错误

python - 在 Django 中获取查询对象的外键值

python - 导入错误 : cannot import name timezone pythonanywhere

django - 使用Django表单显示和编辑?

用于动画 map 可视化的 Python 库