When to override get method in Django CBV?

前端 未结 2 1601
温柔的废话
温柔的废话 2021-01-27 12:23

I\'ve been learning Django and one source of confusion I have is with class based views and when to override the get method. I\'ve looked through the documentation and it explai

2条回答
  •  生来不讨喜
    2021-01-27 13:10

    If you are using the builtin generic views, then you should rarely have to override get(). You'll end up either duplicating lots of functionality, or break features of the view.

    For example, the paginate_by option will no longer work in your view, because you are not slicing the queryset in your get() method.

    If you are using a generic class based view like ListView, you should try to override specific attributes or methods where possible, rather than overriding get().

    The advantage of your view which overrides get() is that it's very clear what it does. You can see that the view fetches a queryset, includes it in a context, then renders the templates. You don't need to know about ListView to understand the view.

    If you like the explicitness of overriding get() subclass View instead. You aren't using any of the features of ListView, so it doesn't make sense to subclass it.

    from django.views.generic import View
    
    class ExampleView(View):
        template_name = 'ppm/ppm.html'
    
        def get(self, request):
            ...
    

提交回复
热议问题