How do you access models from other installed apps in Django when in the same subdirectory?

痞子三分冷 提交于 2019-12-04 06:19:24

问题


I have the following structure for my project:

myproject/
|-- myproject/
|   |-- __init__.py
|   |-- settings.py
|   |-- urls.py
|   |-- wsgi.py
|-- apps/
|   |-- dashboard/
|   |    |-- static/
|   |    |-- templates/
|   |    |-- __init__.py
|   |    |-- admin.py
|   |    |-- apps.py
|   |    |-- forms.py
|   |    |-- models.py
|   |    |-- tests.py
|   |    |-- views.py
|   |-- data/
|   |    |-- __init__.py
|   |    |-- apps.py
|   |    |-- models.py
|   |    |-- router.py
|   |    |-- tests.py
|   |-- __init__.py
|-- manage.py

The settings file has these installed apps added:

'apps.data',
'apps.dashboard',

In the main project I can import from the apps I've created no issues. However, the dashboard app is dependant on the data app and I can't seem to import from the data app.

urls.py imports 'import apps.dashboard.views' with no issues but I've tried a number of things to import the models from data into dashboard. I'm using the models from data in the dashboard views.

None of the following work:

from data.models import ModelName
from apps.data.models import ModelName
from .data.models import ModelName
from .apps.data.models import ModelName

I get 'ImportError: No module named data.models' regardless.

In the apps.py files the DataConfig class has the names set to 'dashboard' and 'data'.

Can anyone explain how I can access the models from data in dashboard?

Thanks


回答1:


from .data.models is an import relative to the current directory where that file exists, e.g., it would be looking for a data module directory inside your dashboard directory. If you want to refer to the data module relative to your dashboard module you should be able to use

from ..data.models import Foo

Using absolute imports depends on your PYTHONPATH environment variable. You can play around with it by adjusting sys.path in a Python REPL.




回答2:


From the top of my head I can advise a few things:

  1. Check your __init__.py files if they are not empty you'll have access to only whats imported in them.
  2. Check if you are not running into circular imports - if in dashboard.models you import from data.models when it imports from dashboard.models.
  3. from apps.data import models or from apps.data.models import ModelName seems the right way to go - knowing this look for solutions.


来源:https://stackoverflow.com/questions/42585884/how-do-you-access-models-from-other-installed-apps-in-django-when-in-the-same-su

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!