What's the suggested way of importing modules within a django project
This has always bothered me, and I've never really come up with my own preferred way of doing this.
When importing something from one of your own applications in a django project, do you import开发者_运维技巧 with:
from myproject.mymodule.model import SomeModel
from myproject.anotherone.model import AnotherModel
or, do you do:
from mymodule.model imoprt SomeModel
from anotherone.model import AnotherModel
Of course, either will work as long as you set your PYTHONPATH
correctly when deploying. Even a combination of the two within a given project will work.
My issue with the second form is when you have a utils.py
or the like sitting in the your project.
# This feels wrong
import utils
But, that could just be me.
Which one is better and why?
I would recommend using the second alternative:
from mymodule.model import SomeModel
from anotherone.model import AnotherModel
In Django, it's recommended to write reusable applications, that you may deploy in multiple projects. Specifying the name of the project would hinder this possibility. It would even complicate the case where you simply change the name of the top project folder!
This is the tradition that most django applications use (e.g. pinax, django contrib, etc).
For more details, you should listen to DjangoCon 2008: Reusable Apps.
I prefer to use absolute imports whenever possible. The first reason is that relative imports are on their way out in Python 3, so it's best not to get into that habit. (Based on the way you phrased the question, I'm assuming that you put the application packages inside your project package.) The second reason is that it makes the intent of what you're importing more explicit.
Though my absolute best practice is to not put my application packages inside the project package. That way, it's easier to move the applications around, and when you use absolute imports inside the package, if you use the same application later inside a differently-named project, you won't have to rewrite all the imports to reflect the different project name.
How are you packaging your modules normally? If you're packaging them all under the "myproject" module, you should just keep doing that. If you're not, there's no reason to start. I don't see that being in a Django project has anything to do with the question--if you're not reusing code, why bother segregating your packages?
But really, the bigger point is that you're not thinking about how to package and distribute your libraries in a broader sense. Even if they're just a collection of handy utility routines, and you don't intend to share them, you should be thinking about namespace issues. The Python Tutorial has a good basic discussion of the concepts.
精彩评论