How do you access models from other installed apps

2020-05-02 08:12发布

问题:

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.