基于类的视图 VS 基于函数的视图 [英] Class Based Views VS Function Based Views

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

问题描述

我在创建 django 应用程序时总是使用 FBV(基于函数的视图),因为它很容易处理.但大多数开发人员表示,最好使用 CBV(基于类的视图),如果是复杂的视图,使用 CBV 实现起来会很痛苦,那么最好只使用 FBV.

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.

为什么?使用 CBV 的优势是什么?

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.

此外,django 附带了一组通用视图类,可用于执行一些最常见的任务.例如,DetailView 类用于从您的模型之一传递单个对象,使用模板呈现它并返回 http 响应.您可以将其直接插入您的 url 配置中..

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.

一个很好的起点是阅读 docs(Django 3.2+).

A nice place to start with this is having a good read of the docs (Django 3.2+).

更新

ccbv.co.uk 提供有关您已经可以使用的基于类的视图的全面且易于使用的信息你.

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天全站免登陆