简体   繁体   English

为什么从 . 导入视图工作和导入视图不?

[英]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 foosys.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.

相关问题 从views.py导入无法从应用程序工作 - import from views.py does not work from app 变量导入在views.py中不起作用 - Variable import does not work in views.py 为什么Celery在Python shell中工作,但在我的Django视图中却没有? (进口问题) - Why does Celery work in Python shell, but not in my Django views? (import problem) 为什么这个导入工作? - Why does this import work? Django视图不存在或无法导入 - Django views does not exist or could not import “from .import views”:未解决的导入 - "from . import views": Unresolved import 为什么“从文件导入类工作”而不是“导入文件”工作? - Why does “from file import class work”, and not “import file”? 为什么“from PIL import Image”不起作用,而“from pil import Image”却起作用? (小写的 pil) - Why does "from PIL import Image" not work, but "from pil import Image" does? (lowercase pil) 为什么“导入PIL; PIL.Image”不行,但是“from PIL import Image”可以吗? - Why does “import PIL; PIL.Image” not work, but “from PIL import Image” does? 为什么要导入<package>不工作,但进口<package.submodule>工作?</package.submodule></package> - Why does import <package> not work ,but import <package.submodule> work?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM