I have a project where the directory structure looks like:
mywebsite/
manage.py
__init__.py
myapp/
models/
__init__.py
base.py
myapp/models/base.py contains:
class X(object):
pass
myapp/models/__init__.py contains:
from base import X
Now, if I do manage.py shell I can have the following session:
> import mywebsite.myapp.models
> import myapp.models
> mywebsite.myapp.models.X == myapp.models.X
False
However if I change myapp/models/__init__.py to be:
from myapp.models.base import X
Then I get True as expected.
I think I am missing something about how imports work or how Django changes paths when using manage.py shell.
Can anyone explain this?
When you open a Django shell, it adds the path to your project to
sys.path. You can see this by runningimport sys; print sys.pathon a Django shell and on a normal python shell and comparing the output. You will note that the output from the Django shell includes the path to themywebsitedirectory as the first item of the list.Basically, it means that the two imports create two different module objects, since they are gotten from different points in the search path. The comparison check returns False since the module objects have different id’s (memory address)