我今天读到Django 1.3 alpha版本已经发布,其中最受瞩目的新功能是引入了基于类的视图。
我已经阅读了相关文档,但我发现很难看出使用它们可以获得什么显著优势™,因此我在这里请求一些帮助来理解它们。
让我们从文档中选取一个高级示例。
urls.py
from books.views import PublisherBookListView
urlpatterns = patterns('',
(r'^books/(\w+)/$', PublisherBookListView.as_view()),
)
视图.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"),
)
视图.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原则
提前感谢任何有贡献的人!
P.S. 对于那些可能会想知道的人,我从来没有被通用视图迷住过:一旦我需要一些高级功能,它们就变得和常规视图一样长了。