[英]Why does from . import views work and import views does not?
This question came to my mind while exploring Django.在探索 Django 时,我想到了这个问题。
Suppose this structure:假设这个结构:
.
├── db.sqlite3
├── manage.py
├── mysite
│ ├── asgi.py
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
└── myapp
├── admin.py
├── apps.py
├── __init__.py
├── migrations
│ └── __init__.py
├── models.py
├── tests.py
├── urls.py
└── views.py
In myapp/urls.py , this statement import views fine:在myapp/urls.py 中,这个语句导入视图很好:
from . import views
while just import views
raises ModuleNotFoundError.而只是
import views
会引发 ModuleNotFoundError。
What I understand is that import foo
searches for foo in a list of directories defined by sys.path
which includes the current package, and also from the documentation :我的理解是
import foo
在sys.path
定义的目录列表中搜索 foo ,其中包括当前包,也从文档中搜索:
Relative imports use leading dots.
相对导入使用前导点。 A single leading dot indicates a relative import, starting with the current package.
单个前导点表示从当前包开始的相对导入。
So, both import foo and from .因此,都导入 foo 和 from 。 foo should work quite the same.
foo 应该完全一样。 If that is true, why it isn't the case for the django imports?
如果这是真的,为什么 django 进口不是这种情况? If it's not true, what do I misunderstand?
如果这不是真的,我有什么误解?
there is no module called views
.没有名为
views
模块。
there is no absolute path that starts with views
.没有以
views
开头的绝对路径。
if you want to import your views from .views
you can do this:如果你想从
.views
导入你的视图,你可以这样做:
from .views import YourView
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.