相对进口

时间:2013-02-08 07:08:59

标签: django

我正在阅读Two Scoops Django最佳实践,以提高我的编码风格。我是相对导入的,下面是使其可重用的示例代码。

Old Way:
from cones.foo import bar

New way:
from .foo import bar

上面的代码适用于cones应用,如果我在其他应用中调用其他模型该怎么办?我必须这样说:

from .foo import bar
from .other import sample

OR

from .foo import bar
from test.other import sample

正确的方法是什么?

2 个答案:

答案 0 :(得分:18)

我通常仅出于某种原因使用这样的导入

from .foo import bar
from .other import sample

原因是 如果明天,我的模块名称从'test'变为'mytest',则代码不需要重构。代码工作没有破坏。

更新

所有以“。”开头的导入dot,仅在 该模块中运行。 交叉模块导入需要整个路径。

答案 1 :(得分:3)

如果test是另一个应用,

from .other import sample

不会工作。

<强>更新

当您从同一个应用程序导入时,您只能使用相对导入。

内部test app

from .other import sample

会奏效。但是你仍然需要完整的表格

from cones.foo import bar

如果您从foo app。

导入test中定义的方法

回答你的问题,第二种方式是正确的方法。

相关问题