将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
quick 的解释是:当您从视图中输入时,导入view1
Python将在以下位置查找view1
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.
使用这种解决方案,您可能无需更改 import
或 urlpattern
s 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屋!