programing tip

클래스 기반보기의 장점은 무엇입니까?

itbloger 2020. 10. 6. 07:56
반응형

클래스 기반보기의 장점은 무엇입니까?


나는 오늘 Django 1.3 알파가 출시되고 있으며 가장 선전 된 새로운 기능은 클래스 기반 뷰 의 도입이라고 읽었습니다 . 관련 문서를
읽었 지만 이를 사용하여 얻을 수 있는 큰 이점 ™ 을보기가 어려우 므로 여기에서이를 이해하는 데 도움을 요청합니다. 문서에서 고급 예제살펴 보겠습니다 .

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 준수

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/

참고URL : https://stackoverflow.com/questions/4370650/what-is-the-advantage-of-class-based-views

반응형