我今天读到Django 1.3 alpha正在发售,而最引人注目的新功能是引入class-based views .
我已经阅读了relevant documentation,但我发现很难看到我可以通过使用它们获得的巨大优势,所以我在这里要求一些帮助来理解它们 .
我们从文档中取一个advanced example .
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标准
有什么东西我不见了吗?我为什么要用它们?文档上有那些?如果是这样,那么理想的用例是什么? mixin有用吗?
提前感谢任何贡献者!
P.S. 对于那些可能想知道的人,我也从未被通用视图所吸引:只要我需要一些高级功能,它们就不会比常规视图更短 .