在django框架之外使用django模型 [英] using django model outside of the django framework
本文介绍了在django框架之外使用django模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
import sys
import os
sys.path.append(os.path.abspath(/ home / pi / garageMonitor / django / garageMonitor))
os.environ ['DJANGO_SETTINGS_MODULE'] ='garageMonitor.settings'
导入模型
config = models.SystemConfiguration.objects.filter(idSystemConfiguration = 1)
config = config [0]
for x in config .__ dict__:
print x
这是我得到的错误:
文件/home/pi/garageMonitor/django/lib/webWatcher.py,第14行在< module>
导入模型
文件/home/pi/garageMonitor/django/garageMonitor/models.py,第11行在< module>
class DoorClosing(models.Model):
文件/usr/local/lib/python2.7/dist-packages/django/db/models/base.py,第131行,__new__
'app''%(new_class .__ name__,model_module .__ name__)
django.core.exceptions.ImproperlyConfigured:无法检测模型DoorClosing
DoorClosing是我的models.py文件中的一个类,类似的代码在django框架内工作,我缺少什么?
解决方案
运行
django.setup()$ b $在导入模型之前,b
import django
import sys
import os
sys.path.append(os.path.abspath(/ home / pi / garageMonitor / django / garageMonitor )
os.environ ['DJANGO_SETTINGS_MODULE'] ='garageMonitor.settings'
django.setup()
导入模型
config = models.SystemConfiguration.objects.filter(idSystemConfiguration = 1)
confi g = config [0]
在配置中的x。_ dict_:
print x
请参阅 https://docs.djangoproject.com/en/1.9 / ref / applications /#initialization-process
I have a django application that is working fine. I want to be able to leverage the model to access the database from another (standalone) python app. Here is what I have (that doesn't work.)
import sys
import os
sys.path.append(os.path.abspath("/home/pi/garageMonitor/django/garageMonitor"))
os.environ['DJANGO_SETTINGS_MODULE'] = 'garageMonitor.settings'
import models
config = models.SystemConfiguration.objects.filter(idSystemConfiguration=1)
config = config[0]
for x in config.__dict__:
print x
Here is the error I get:
File "/home/pi/garageMonitor/django/lib/webWatcher.py", line 14, in <module>
import models
File "/home/pi/garageMonitor/django/garageMonitor/models.py", line 11, in <module>
class DoorClosing(models.Model):
File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 131, in __new__
'app.' % (new_class.__name__, model_module.__name__)
django.core.exceptions.ImproperlyConfigured: Unable to detect the app label for model "DoorClosing
DoorClosing is a class in my models.py file. Similar code works within the django framework. What am I missing?
解决方案
run
django.setup()
before importing your models
import django
import sys
import os
sys.path.append(os.path.abspath("/home/pi/garageMonitor/django/garageMonitor"))
os.environ['DJANGO_SETTINGS_MODULE'] = 'garageMonitor.settings'
django.setup()
import models
config = models.SystemConfiguration.objects.filter(idSystemConfiguration=1)
config = config[0]
for x in config.__dict__:
print x
see https://docs.djangoproject.com/en/1.9/ref/applications/#initialization-process
这篇关于在django框架之外使用django模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文