开发者

import strategy within django applications

I would like to know what is the best import strategy within django reusable applications.

Say I have an application called usefulapp. Inside my app, I will need to access, say, the models. Should I use an explicit import as:

import usefulapp.models

or simply, since I am inside this very app, I could use:

import models

Which one is recommended?

Are there disadvantage开发者_StackOverflows of using the second approach?


The second approach assumes that . is in sys.path before any other directories that may contain a models module. There is no requirement that . be in it at all, so importing either via relative imports or via the app is best.


I personally, try to keep the convention of always importing from the app.

Don't import from the project, because project name can change; your app can be used in some other project (at least you are supposed to make apps like that).

Don't import from models directly because, as Ignacio rightly mentions, it is not necessary that . is in the python path.

But, App names are always on the python path. Django adds them to the python path (via set_environ(settings)), on the top of the list, so you can be rest assured that the right files are always picked up.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜