Django:将views.py分割成多个文件 [英] Django: split views.py in several files
问题描述
我的views.py变得太大了,很难找到正确的视图。那么如何将它分割成几个文件,然后导入呢?是否涉及任何速度损失?我可以使用models.py吗?
在Django中,一切都是一个Python模块(* .py)。您可以创建一个包含 __ init __。py
的视图文件夹,您仍然可以导入视图,因为这也实现了一个Python模块。但是一个例子会更好。
您原来的 views.py
可能如下所示:
def view1(arg):
pass
def view2(arg):
pass
使用以下文件夹/文件结构,它将工作相同:
views /
/ pre>
__init__.py
viewsa.py
viewb.py
viewsa.py
:def view1(arg):
pass
viewsb.py
:def view2(arg):
pass
__ init __。py
:从viewa导入视图1
from viewsb import view2
快速的解释将是:当您从视图中输入
import view1
Python将寻找view1
views.py
,这是什么第一(原件)案例中的笔
views / __ init __。py
第二种情况。这里,__ init __。py
能够提供view1方法,因为它导入它。
使用这种解决方案,您可能无需更改
import
或urlpattern
s参数urls.py
如果每个新视图文件中有很多方法,您可能会发现对使
视图/ __ init __。py
中的导入使用*
,如下所示:from viewsa import *
from viewsb import *
我实际上不知道速度问题(但我怀疑有什么)。
对于模型可能有点困难。
My views.py has become too big and it's hard to find the right view. So how do i split it in several files and then import it? Does it involve any speed loss? Can i do the same with models.py?
解决方案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.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
The quick explanation would be: when you write
from views import view1
Python will look for view1 in
views.py
, which is what happens in the first (original) case
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.With this kind of solution, you might have no need to change
import
orurlpattern
s arguments inurls.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.
这篇关于Django:将views.py分割成多个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!