[Fixed]-Relative Imports in Django


I usually use imports like this only for one reason

from .foo import bar
from .other import sample

The reason being
If Tomorrow, my module name changes from say ‘test’ to ‘mytest’ then the code does not require a refactoring. The code works without breaking.


All imports starting with a ‘.’ dot, only works within that package.
Cross package imports need require the whole path.


If test is another app,

from .other import sample

wont work.


You can only use relative imports when you’re importing from the same app.

Inside test app

from .other import sample

will work. But you’ll still need the complete form

from cones.foo import bar

if you import method defined in foo from test app.

So answering your question the second way is the correct way.

Leave a comment