问题描述
我正在开发一个Web项目并使用Django。在我的 views.py
文件中,我想访问要为其导入模型
的数据库。
I'm working on a webproject and using Django. In my views.py
file I want to access the database for which I want to import my models
.
这是我的目录结构:
├── project
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
├── app
│ ├── admin.py
│ ├── __init__.py
│ ├── models.py
│ ├── tests.py
│ └── views.py
├── manage.py
在我的视图中.py
我在做导入模型
,但是却出现了 importError
。尽管来自。导入模型
有效。
In my views.py
I'm doing import models
, but I'm getting an importError
. Although from . import models
works.
为什么?
但是以下方法可以正常工作:
But the following works without any error:
├── __init__.py
├── mod1.py
└── mod2.py
mod1.py
import mod2
print(mod2.foo())
mod2.py
def foo():
return "Hello"
推荐答案
导入模型
的问题是您不知道它是否绝对导入或相对导入。模型可以是python路径中的模块,也可以是当前模块中的软件包。
The problem of import models
is that you don't know whether its an absolute import or a relative import. models could a module in python's path, or a package in the current module.
当本地软件包与python标准库软件包同名时,这很烦人。 / strong>
This is quite annoying when a local package has the same name as a python standard library package.
您可以从__future__ import absolute_import 中执行,这将完全关闭隐式相对导入。在 PEP 328中对此进行了描述,包括有关歧义的理由。一个>。我相信Python 3000的隐式相对导入已完全关闭。
You still can do relative imports, but you have to do them explicitly, like this:
Hence, relative imports
from . import models
work, whereas absolute imports, import models
don't.
这篇关于来自。导入模型有效,但导入模型无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!