Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
261 views
in Technique[技术] by (71.8m points)

python - Django Standalone Script

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

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.

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

I get:

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...