Split views.py in several files

前端 未结 10 862
有刺的猬
有刺的猬 2020-11-27 09:37

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 l

10条回答
  •  北荒
    北荒 (楼主)
    2020-11-27 09:59

    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

    1. views.py, which is what happens in the first (original) case

    2. 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 or urlpatterns arguments in urls.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.

提交回复
热议问题