本文介绍了来自。导入模型有效,但导入模型无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个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 can do from __future__ import absolute_import which turns off implicit relative imports altogether. It is described, including with this justification about ambiguity, in PEP 328. I believe Python 3000 has implicit relative imports turned off completely.

您仍然可以进行相对导入,但必须显式地进行相对导入,例如:

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.

这篇关于来自。导入模型有效,但导入模型无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

查看更多