I'm working on a webproject and using Django. In my views.py
file I want to access the database for which I want to import my models
.
Here's my directory structure:
├── project
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
├── app
│ ├── admin.py
│ ├── __init__.py
│ ├── models.py
│ ├── tests.py
│ └── views.py
├── manage.py
In my views.py
I'm doing import models
, but I'm getting an importError
. Although from . import models
works.
Why?
But the following works without any error:
├── __init__.py
├── mod1.py
└── mod2.py
mod1.py
import mod2
print(mod2.foo())
mod2.py
def foo():
return "Hello"
In order to use an absolute import, you need to refer to the full package.sibling combo:
import app.models
from app import models
from app.models import mymodel
However, explicit relative imports are an acceptable alternative to absolute imports:
from . import models
from .models import mymodel
You should really read PEP-8 on imports for a great explanation about importing packages.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With