我今天读到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):
# 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
现在,让我们将其与我自己在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)
return render_to_response('books/books_by_publisher.html', {
"book_list": book_list,
"publisher": publisher,
}, context_instance=RequestContext(request))
我看到的第二个版本是:
- 功能等效
- 更具可读性(
self.args[0]
?太糟糕了!) - 更短
- 符合DRY的要求
我缺少什么大东西吗?我为什么要使用它们?这些在文档上吗?如果是这样,那么理想的用例是什么?是否混入那有用吗?
在此先感谢任何贡献者!
PS对于那些可能会想知道的人,我也从来没有被通用视图所吸引:只要我需要一些高级功能,它们就会比普通视图更短。