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.
If self.args[0]
is bothering you, the alternative is:
urlpatterns = patterns('books.views',
url(r'^books/(?P<slug>\w+)/$', 'publisher_books_list', name="publisher_books_list"),
)
Then you could use self.kwargs['slug']
instead, making it slightly more readable.
Your example function and class are not equal in features.
The class based version provide pagination for free and forbid the use of other HTTP verbs than GET.
If you want to add this to your function, it's going to be much longer.
But it is, indeed, more complicated.
This is the first I'm hearing of this -- and I like it.
The advantage I see here, honestly, is that it makes views more consistent with Django overall. Models are classes and I've always felt that views should be too. I know not everything is but views and models are the two heavily used types.
As for the technical advantage? Well, in Python everything is a class (or object?) -- so is there really a difference? Isn't it 99% syntactical sugar in the first place?
One way to think about class based views, is that they are like a the Django admin with training wheels off and therefore a lot more flexible (but more difficult to understand).
For example the list-display in the admin is clearly based on the generic ListView. The simplest list view you would only define a model or queryset.
class MyExampleView(ListView);
model = ExampleModel
You will need to supply your own template, but it will basically be the same as the most basic ModelAdmin. The list_display attribute in the model admin will tell it what fields to display, whereas in the ListView you would do this in the template.
class SpeciesAdmin(admin.ModelAdmin):
list_display = ['name']
admin.site.register(ExampleModel , ExampleModelAdmin)
With the admin you have a parameter
list_per_page = 100
which defines how many objects per page. List view has
paginate_by = 100
which achieves the same thing. Likewise if you look into customising the admin heavily, you will see a lot of overlap.
This site here should give you a better idea of what they do as well.
http://ccbv.co.uk/
精彩评论