基于类的视图VS基于功能的视图 [英] Class Based Views VS Function Based Views

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

问题描述

在创建django应用程序时,我总是使用FBV(基于功能的视图),因为它很容易处理。但是大多数开发人员表示,使用CBV(基于类的视图)最好使用FBV,如果复杂的视图是使用CBV实现的难度。



为什么?使用CBV有什么优势?

解决方案

唯一最重要的优点是继承。在大型项目中,您可能会有很多类似的观点。而不是一次又一次地编写相同的代码,您可以简单地从基本视图继承您的视图。



此外,django还附带一个通用视图类的集合,可以是曾经做过一些最常见的任务。例如,DetailView类用于从一个模型传递单个对象,并使用模板进行渲染并返回http响应。你可以直接插入你的url conf ..

  url(r'^ author /(?P< pk> \ d +)/ $',DetailView.as_view(model = Author)),

或者你可以扩展它使用自定义功能

  class SpecialDetailView(DetailView):
model =作者
def get_context_data(self,* args,** kwargs):
context = super(SpecialDetailView,self).get_context_data(* args,** kwargs)
上下文['books'] = Book.objects.filter(popular = True)
返回上下文

现在,您的模板将通过一组书对象进行渲染。 / p>

从这开始,一个不错的选择是读取 docs



更新



ccbv.co.uk 具有全面和简洁y使用您已经可以使用的基于类的视图的信息。


I always use FBVs (Function Based Views) when creating a django app because it's very easy to handle. But most developers said that it's better to use CBVs (Class Based Views) and use only FBVs if it is complicated views that would be a pain to implement with CBVs.

Why? What are the advantages of using CBVs?

解决方案

The single most significant advantage is inheritance. On a large project it's likely that you will have lots of similar views. Rather than write the same code again and again, you can simply have your views inherit from a base view.

Also django ships with a collection of generic view classes that can be used to do some of the most common tasks. For example the DetailView class is used to pass a single object from one of your models, render it with a template and return the http response. You can plug it straight into your url conf..

url(r'^author/(?P<pk>\d+)/$', DetailView.as_view(model=Author)),

Or you could extend it with custom functionality

class SpecialDetailView(DetailView):
    model = Author
    def get_context_data(self, *args, **kwargs):
        context = super(SpecialDetailView, self).get_context_data(*args, **kwargs)
        context['books'] = Book.objects.filter(popular=True)
        return context

Now your template will be passed a collection of book objects for rendering.

A nice place to start with this is having a good read of the docs.

Update

ccbv.co.uk has comprehensive and easy to use information about the class based views you already have available to you.

这篇关于基于类的视图VS基于功能的视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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