将 views.py 拆分为多个文件 [英] Split views.py in several files
问题描述
我的 views.py
变得太大了,很难找到合适的视图.
My views.py
has become too big and it's hard to find the right view.
如何将其拆分为多个文件然后导入?是否涉及任何速度损失?
How do I split it in several files and then import it? Does it involve any speed loss?
我可以用 models.py
做同样的事情吗?
Can I do the same with models.py
?
推荐答案
在 Django 中,一切都是 Python 模块 (*.py).你可以创建一个带有 __init__.py
的视图文件夹,你仍然可以导入你的视图,因为这也实现了一个 Python 模块.但举个例子会更好.
In Django everything is a Python module (*.py). You can create a view folder with an __init__.py
inside and you still will be able to import your views, because this also implements a Python module. But an example would be better.
您的原始 views.py
可能如下所示:
Your original views.py
might look like this :
def view1(arg):
pass
def view2(arg):
pass
使用以下文件夹/文件结构,它的工作方式相同:
With the following folder/file structure it will work the same :
views/
__init__.py
viewsa.py
viewsb.py
viewsa.py
:
def view1(arg):
pass
viewsb.py
:
def view2(arg):
pass
__init__.py
:
from viewsa import view1
from viewsb import view2
快速解释是:当你写from views import view1
时,Python会在
The quick explanation would be: when you write from views import view1
Python will look for view1 in
views.py
,这是第一个(原始)案例中发生的事情
views.py
, which is what happens in the first (original) case
views/__init__.py
,这就是第二种情况.在这里,__init__.py
能够提供 view1 方法,因为它导入了它.
views/__init__.py
, which is what happens in the second case. Here, __init__.py
is able to provide the view1 method because it imports it.
使用这种解决方案,您可能无需更改 urls.py
With this kind of solution, you might have no need to change import
or urlpattern
s arguments in urls.py
如果你在每个新的视图文件中有很多方法,你可能会发现让 views/__init__.py
中的导入使用 *
很有用,像这样:
If you have many methods in each new view file, you might find it useful to make the imports in views/__init__.py
use *
, like this:
from viewsa import *
from viewsb import *
我实际上不知道速度问题(但我怀疑是否存在).
I actually don't know about speed issues (but I doubt there are any).
对于模型来说,这可能有点困难.
For Models it might be a bit difficult.
这篇关于将 views.py 拆分为多个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!