本文介绍了Django:分解视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这实际上只是一个最佳实践"问题...

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

我发现在开发应用程序时,我经常会看到很多的视图.

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

将这些视图分成几个视图文件是一种常见的做法吗?换句话说......而不是只有views.py,views_1.py、views_2.py、views_3.py(但命名更恰当,也许是按类别)是否很常见?

Is it common practice to break these views up into several view files? In other words... instead of just having views.py, is it common to have views_1.py, views_2.py, views_3.py (but named more appropriately, perhaps by category)?

推荐答案

拆分 views.py

您的大部分代码可能希望您的视图可以作为 myapp.views.viewname 访问.我见过人们分解他们的视图但保留这个 python 名称的一种方法是创建一个 views/ 目录.views/__init__.py 将有:

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 *

然后,在views/foo_views.py中,输入:

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

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

def your_other_view(...):
    # ...

等等.因此,您将 views.py 中的所有内容移动到此目录中的文件中,创建 __init__.py,删除 views.py,然后就完成了.

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

然后,当你import myapp.views时,myapp.views.foo_detail会引用你在views/foo_views.py中定义的函数代码>.

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

这个策略也适用于 admin.py 等.但是如果你想像这样拆分 models.py,您需要将 app_label = 'your_app_name' 添加到所有模型的 class Meta: 中.例如,unicorn_app/models/unicorns.py 可以有这样的条目:

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'

(否则,Django 认为 Unicorn 模型是名为models"的 Django 应用程序的一部分,这会弄乱管理站点.当前到 1.6 - 即将发布的 1.7 版本将删除此要求.)

(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.)

这篇关于Django:分解视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 22:01
查看更多