Django独立脚本 [英] Django Standalone Script

查看:77
本文介绍了Django独立脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从另一个python脚本访问Django(v1.10)应用数据库,但这样做有些麻烦。

I am trying to access my Django (v1.10) app DB from another python script and having some trouble doing so.

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

This is my file and folder structure:

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的文档我的 other_script.py 看起来像这样:

In accordance with Django's documentations my other_script.py looks like this:

import django
from django.conf import settings

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

from store.store_app.models import MyModel

但是它会生成运行时错误:

But it generates a runtime error:

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 作为其最后一个元素。

I should note that my INSTALLED_APPS list contains store_app as its last element.

如果相反,我尝试通过这样的配置:

If instead I try to pass a config like this:

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 我又遇到了另一个有关缺少的属性的错误,依此类推。

If I edit settings.py and add LOGGING_CONFIG=None I get another error about another missing attribute, and so on.

任何建议都会受到赞赏。

Any suggestions will be appreciated.

推荐答案

尝试一下

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

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

This script you can use anywhere in your system.

这篇关于Django独立脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆