Answer the question
In order to leave comments, you need to log in
What do you choose and why? FBV (function views) vs CBV (class views) in Django?
Back in those distant times (2 years ago), when I was just starting to learn Python, one postulate from the philosophy of this wonderful language sunk into my head: Explicit is better than implicit.
And after a while I started learning Django.
Learned how the view function works:
def view(request):
queryset = Model.objects.all()
context = {'qs':queryset}
return render(request, 'template.html', context)
class View(ListView):
queryset = Model.objects.all()
template_name = "template.html"
{% for obj in object_list &}
{{ obj.object_from_db}}
{% endfor %}
{{ qs }}
Answer the question
In order to leave comments, you need to log in
I choose CBV. They are easier to read, each part is separated. Separately getting the queryset, separately initializing the form, and so on. In FBV, everything is lumped together and in any more or less non-trivial case, the function quickly grows in size and becomes less and less clear. Especially when you start using huge operators if
to separate the parts that handle POST
and GET
. Over time, FBVs grow and become less and less readable.
A big advantage of CBVs is also that they can be inherited from each other. When it becomes necessary to make several Views with similar functionality, this approach allows you to radically reduce the amount of code and increase its understandability.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question