Function-Based Views (FBV) VS. Class Based Views (CBV)

5

When creating a project in Django, let's say, of relative complexity and size, I have always been inclined to use FBV since I find them easier to use. Some say that it is better to use CBV because they have some advantages such as the inheritance provided by the OOP and less amount of code.

Despite the advantages of the CBV, I still find them a little harder to follow:

What are the advantages of CBV over FBV?

    
asked by César 02.12.2015 в 13:34
source

1 answer

8

I believe that one of its main advantages is the elimination of repeated code.

CBVs are, from my point of view, more efficient than function-based views because they reduce the code needed to produce the expected result. This reduction not only adds clarity to the code, it also facilitates understanding and maintenance of the code.

The use of class-based views has a positive impact on other elements of the application by allowing a better structure of models and URL patterns, for example.

To illustrate the advantages of class-based views, I add a real example.

In a document control application, the document model has the get_absolute_url method that looks like this:

def get_absolute_url(self):
    return reverse('detalle', kwargs={'pk': self.id})

And in the file urls.py a a search pattern related to the previous method:

url(r'^(?P<pk>\d+)/control$', DetalleDocumento.as_view(), name='detalle'),

With these two elements, the view based on the respective class is reduced to the following:

class DetalleDocumento(DetailView):
    model = Documento
    template_name = "docs/detalle.html"

And template_name , by the way, is an optional parameter.

This is the main advantage of the CBV: the code is reduced to its minimum expression, but does not lose legibility or efficiency. In addition CBVs work in most situations, so Django's DRY principle becomes apparent.

    
answered by 03.12.2015 / 06:18
source