【问题标题】:using django model outside of the django framework在 django 框架之外使用 django 模型
【发布时间】:2016-03-21 21:50:24
【问题描述】:

我有一个运行良好的 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 框架中工作。我错过了什么?

【问题讨论】:

标签: python django


【解决方案1】:

运行

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

【讨论】:

    【解决方案2】:

    请参阅此帖子以了解最新 Django 版本中此问题的工作版本。 见https://stackoverflow.com/a/46050808/1698030

    在这里引用解决方案:

    import os
    from django.conf import settings
    from django.apps import apps
    
    conf = {
        'INSTALLED_APPS': [
            'Demo'
        ],
        'DATABASES': {
            'default': {
                'ENGINE': 'django.db.backends.sqlite3',
                'NAME': os.path.join('.', 'db.sqlite3'),
            }
        }
    }
    
    settings.configure(**conf)
    apps.populate(settings.INSTALLED_APPS)
    

    将您的应用名称和您项目中的任何其他应用放在“INSTALLED_APPS”下

    【讨论】:

      猜你喜欢
      • 2017-03-27
      • 2023-03-04
      • 2015-10-28
      • 1970-01-01
      • 1970-01-01
      • 2014-11-11
      • 2015-01-28
      • 2013-04-26
      • 2018-12-10
      相关资源
      最近更新 更多