我今天读到Django 1.3 alpha正在发售,最引人注目的新功能是引入基于类的视图.
我已经阅读了相关的文档,但我发现很难看到使用它们可以获得的大优势,所以我在这里要求一些帮助来理解它们.
让我们从文档中获取一个高级示例.
from books.views import PublisherBookListView
urlpatterns = patterns('',
(r'^books/(\w+)/$', PublisherBookListView.as_view()),
)
Run Code Online (Sandbox Code Playgroud)
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 …Run Code Online (Sandbox Code Playgroud)