Django: Breaking up views

前端 未结 3 669
小蘑菇
小蘑菇 2021-02-01 17:52

This is really just a \"best practices\" question...

I find that When developing an app, I often end up with a lot of views.

Is it common practice to br

3条回答
  •  眼角桃花
    2021-02-01 18:06

    Splitting views.py

    Most of your code probably expects your views to be accessible as myapp.views.viewname. One way I've seen people break up their views but keep this python name is to create a views/ directory. views/__init__.py will have:

    from .foo_views import *
    from .bar_views import *
    from .baz_views import *
    

    Then, in views/foo_views.py, put:

    def foo_detail(request, ...):
        # your code here
    
    def foo_list(request, ...):
        # your code here
    
    def your_other_view(...):
        # ...
    

    etc. So you move everything from views.py into files in this directory, make __init__.py, delete views.py, and you're done.

    Then, when you import myapp.views, myapp.views.foo_detail will refer to the function that you defined in views/foo_views.py.

    Splitting other modules

    This strategy should also work fine for admin.py, etc. But if you want to split up models.py like this, you will need to add app_label = 'your_app_name' to the class Meta: of all of your models. For example, unicorn_app/models/unicorns.py could have an entry like this:

    class Unicorn(models.Model):
        description = models.CharField(max_length=80)
    
        class Meta:
            app_label = 'unicorn_app'
    

    (Otherwise, Django imagines that the Unicorn model is part of a Django app named "models", which messes up the admin site. Current through 1.6 - the upcoming 1.7 release will remove this requirement.)

提交回复
热议问题