Django:打破观点 [英] Django: Breaking up views

查看:125
本文介绍了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 ,put:

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'到所有模型的类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 模型是一个名为模特儿的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:打破观点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆