darkhorse
darkhorse

Reputation: 8722

How to import something from one directory above in a Django project?

In my Django project, I have split models. The project directory kinda looks like this:

myproject/
    app1/
        validators.py
        views.py
        __init__.py
        models/
            __init__.py
            model1.py
            model2.py

And of course, the models work properly thanks to this:

#myproject/app1/models/__init__.py:
from .model1 import Model1
from .model2 import Model2

Anyway, in my model1.py module, I want to import a validator from the validators.py module. But as you can see, its one directory above. How can I do this? Preferably, I would want a solution that works in all types of filesystems. Thanks for any answers.

Upvotes: 2

Views: 145

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476594

You can use two consecutive dots here, like:

# myproject/app1/models/__init__.py

from .model1 import Model1
from .model2 import Model2
from ..validators import SomeValidator

But perhaps it is better to use absolute imports here:

# myproject/app1/models/__init__.py

from .model1 import Model1
from .model2 import Model2
from app1.validators import SomeValidator

Upvotes: 1

Related Questions