开发者

import strategy within django applications

开发者 https://www.devze.com 2022-12-22 08:37 出处:网络
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

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

精彩评论

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