python – 在django框架之外使用django模型

我有一个工作正常的
django应用程序.我希望能够利用该模型从另一个(独立)
python应用程序访问数据库.这就是我所拥有的(这不起作用.)

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

这是我得到的错误:

  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是我的models.py文件中的一个类.类似的代码在django框架内工作.我错过了什么?

最佳答案 跑

django.setup()

在导入模型之前

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

https://docs.djangoproject.com/en/1.9/ref/applications/#initialization-process

点赞