从另一个Django项目的应用程序导入一个类

时间:2016-11-01 16:33:45

标签: python django

Django 1.9.7。

我目前的项目结构是:

project1
|  etl 
│   ├── manage.py
│   ├── pipeline
│   │   ├── config.py
│   │   ├── __init__.py
│   │   ├── models.py
│   │   ├── linkage.py
│   │   ├── urls.py
│   │   ├── utils
│   │   ├── views.py
└── web
    ├── manage.py
    ├── rocket
    │   ├── admin.py
    │   ├── __init__.py
    │   ├── models.py
    │   ├── templates
    │   ├── tests.py
    │   ├── urls.py
    │   ├── views.py
    │   ├── apps.py
    ├── db.sqlite3

pipelinerocket都是Django应用。 etlweb都是Django项目。 web使用本地SQLite DB,etl使用远程PostgreSQL DB。

如何将Project课程从project1/web/rocket/models.py导入project1/etl/pipeline/linkage.py

我无法将rocket应用程序移动到目录层次结构中的其他位置。我尝试以多种方式导入它,但没有成功。

方式1

$ head linkage.py
import sys, os
sys.path.append(os.path.join(os.path.dirname(__file__), '../..', 'web/rocket'))
from models import Project

错误:ImportError: cannot import name Project

方式2

$ head linkage.py
import sys, os
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'web'))
from rocket.models import Project

错误:RuntimeError: Model class django.contrib.sites.models.Site doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.

方式3

$ head linkage.py
from ....rocket.models import Project

错误:ValueError: Attempted relative import beyond toplevel package

方式4

$ head linkage.py
from rocket.models import Project

错误:ImportError: No module named cris.models

好的,我认为可能会出现错误,因为我在models.py目录中有一个名称相同的文件etl/pipeline。但即使我只是为了测试,也会将web/rocket/models.py复制到其他文件,例如project1/web/rocket/mytest.py

尝试导入它:

$ head linkage.py
import sys, os
sys.path.append(os.path.join(os.path.dirname(__file__), '../..', 'web/rocket'))
from mytest import Project

我收到以下错误:

  File "/home/trex/Development/Mars/new/rocket/rocket-venv/local/lib/python2.7/site-packages/django/contrib/sites/models.py", line 83, in <module>
    class Site(models.Model):
  File "/home/trex/Development/Mars/new/rocket/rocket-venv/local/lib/python2.7/site-packages/django/db/models/base.py", line 102, in __new__
    "INSTALLED_APPS." % (module, name)
RuntimeError: Model class django.contrib.sites.models.Site doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.

好的,有些消息说我rocket中没有INSTALLED_APPS。所以,我尝试以几种方式在etl/settings/base.py文件中添加它:

方式1

INSTALLED_APPS = [
    'web.rocket'
]

错误:ImportError: No module named web

方式2

INSTALLED_APPS = [
    'web/rocket'
]

错误:ImportError: Import by filename is not supported.

方式3

INSTALLED_APPS = [
    'rocket'
]

错误:ImportError: No module named rocket

0 个答案:

没有答案