基于类视图的优势是什么? [英] What is the advantage of Class-Based views?

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

问题描述

我今天读到Django 1.3 alpha是发货,最引人瞩目的新功能是引入基于类的视图

我已经阅读了相关文档,但是我很难看到使用它们可以获得的大优势™,所以我在这里询问一些帮助了解他们。

让我们来看一下



urls.py



  from books.views import PublisherBookListView 

urlpatterns = patterns('',
(r'^ books /(\w +)/ $',PublisherBookListView.as_view()),



views.py



  from django.shortcuts import get_object_or_404 
from django.views.generic import ListView
from books.models import Book,Publisher

class PublisherBookListView(ListView):

context_object_name =book_list
template_name =books / books_by_publisher.html,

def get_queryset(self):
self.publisher = get_object_or_404(Publisher,name__iexact = self.args [0])
return Book.objects.filter(publisher = self.publisher)

def get_context_data(self,** kwargs):
#首先调用基本实现以获取上下文
context = super(PublisherBookListView,self).get_context_data(** kwargs)
#在发布者中添加
上下文['publisher'] = self.publisher
返回上下文

现在让我们将它与一个平淡的视图解决方案进行比较,我自己在5分钟内为此做出了问题(对于您可能发现的任何错误,我们深表歉意)。



urls.py



  urlpatterns = patterns('books.views',
url(r'^ books /(\w +)/ $','publisher_books_list',name =publisher_books_list ),



views.py



  from django.shortcuts import get_object_or_404 
from books.models import Book,Publisher

def publisher_books_list(request,publisher_name):
publisher = get_object_or_404(Publisher,name__iexact = publisher_name)
book_list = Book.objects.filter(publisher = publisher)

返回render_to_response('books / books_by_publisher.html',{
book_list:book_list,
publisher:publisher,
},context_instance = RequestContext(request))

我的第二个版本看起来如下:




  • 相当于功能

  • 更多的可读性( self.args [0] ?可怕的!)

  • 较短的

  • 不低于DRY


$ b $有没有什么大的东西我失踪了?为什么要使用它们?那些在文件上?那么那么理想的用例是什么呢?



提前感谢任何贡献者!



PS 对于那些可能想知道的人来说,我从来没有被通用视图迷住:只要我需要一些高级功能,他们就不会比常规观点更短。

解决方案

您可以对类进行子类化,并针对特定情况对get_context_data进行细化方法,并按原样保留其余值。您不能使用函数来执行此操作。



例如,您可能需要创建一个新的视图,可以执行前一个操作,但是您需要包含额外的变量在上下文中。将原始视图子类化并覆盖get_context_data方法。



另外,将将模板渲染为单独方法所需的步骤也可以提高更清晰的代码 - 在方法中所做的更少,更容易理解。使用常规的查看功能,它们都被转储到一个处理单元中。


I read today that Django 1.3 alpha is shipping, and the most touted new feature is the introduction of class-based views.
I've read the relevant documentation, but I find difficult to see the big advantage™ that I could get by using them, so I'm asking here for some help in understanding them.
Let's take an advanced example from the documentation.

urls.py

from books.views import PublisherBookListView

urlpatterns = patterns('',
    (r'^books/(\w+)/$', PublisherBookListView.as_view()),
)

views.py

from django.shortcuts import get_object_or_404
from django.views.generic import ListView
from books.models import Book, Publisher

class PublisherBookListView(ListView):

    context_object_name = "book_list"
    template_name = "books/books_by_publisher.html",

    def get_queryset(self):
        self.publisher = get_object_or_404(Publisher, name__iexact=self.args[0])
        return Book.objects.filter(publisher=self.publisher)

    def get_context_data(self, **kwargs):
        # Call the base implementation first to get a context
        context = super(PublisherBookListView, self).get_context_data(**kwargs)
        # Add in the publisher
        context['publisher'] = self.publisher
        return context

And now let's compare it to a "plain-old-views" solution, made by myself in 5 minutes for this question (I apologize for any error you may find in it).

urls.py

urlpatterns = patterns('books.views',
    url(r'^books/(\w+)/$', 'publisher_books_list', name="publisher_books_list"),
)

views.py

from django.shortcuts import get_object_or_404
from books.models import Book, Publisher

def publisher_books_list(request, publisher_name):
    publisher = get_object_or_404(Publisher, name__iexact=publisher_name)
    book_list = Book.objects.filter(publisher=publisher)

    return render_to_response('books/books_by_publisher.html', {
        "book_list": book_list,
        "publisher": publisher,
    }, context_instance=RequestContext(request))

The second version to me looks:

  • Equivalent in functionality
  • A lot more readable (self.args[0]? awful!)
  • Shorter
  • Not less DRY-compliant

Is there something big I'm missing? Why should I use them? Are those on the documentation? If so then what would be the ideal use case? Are mixins that useful?

Thanks in advance to anybody who contributes!

P.S. for those who might wonder, I was never enthralled by generic views as well: as soon as I needed some advanced functionality, they became no shorter than regular views.

解决方案

You can subclass a class and refine methods like get_context_data for specific cases, and leave the rest as-is. You can't do that with functions.

For instance, you might need to create a new view that does everything a previous one does, but you need to include extra variable in the context. Subclass the original view and override the get_context_data method.

Also, separating the steps needed to render the template into separate methods promotes clearer code - the less done in a method, the easier it is to understand. With regular view functions, it's all dumped into the one processing unit.

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

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