Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

from . import models works, but import models doesn't

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"
like image 749
Kartik Anand Avatar asked Dec 20 '22 04:12

Kartik Anand


1 Answers

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.

like image 92
rnevius Avatar answered Dec 21 '22 18:12

rnevius