Interview question
What is the difference between function-based views (FBVs) and class-based views (CBVs) in Django? Django में function-based views (FBVs) और class-based views (CBVs) में क्या अंतर है?
Answer
| Aspect | Function-based views | Class-based views |
|---|---|---|
| Definition | A plain Python function | A Python class extending View or a generic view |
| Code reuse | Harder - duplication across similar views | Easier - inheritance and mixins |
| Readability | Straightforward for simple logic | Can feel 'magic' due to inherited behavior |
| HTTP method handling | Manual if/else on request.method | Separate methods per HTTP verb (get, post, etc.) |
# Function-based view (FBV)
from django.http import HttpResponse
from django.shortcuts import render, get_object_or_404
def book_detail(request, pk):
book = get_object_or_404(Book, pk=pk)
if request.method == 'POST':
# handle form submission
pass
return render(request, 'book_detail.html', {'book': book})
# Class-based view (CBV) - equivalent using View
from django.views import View
class BookDetailView(View):
def get(self, request, pk):
book = get_object_or_404(Book, pk=pk)
return render(request, 'book_detail.html', {'book': book})
def post(self, request, pk):
# handle form submission - separate method, no if/else needed
pass
# urls.py - registering each type
from django.urls import path
from . import views
urlpatterns = [
path('books/<int:pk>/', views.book_detail, name='book-detail-fbv'),
path('books-cbv/<int:pk>/', views.BookDetailView.as_view(), name='book-detail-cbv'),
]
# Generic CBV - even less code for common patterns
from django.views.generic import DetailView
class BookDetailGeneric(DetailView):
model = Book
template_name = 'book_detail.html'
# Automatically handles GET, fetches the object, and renders the template| पहलू | Function-based views | Class-based views |
|---|---|---|
| Definition | Plain Python function | View extend करने वाली class |
| Code reuse | मुश्किल | आसान - inheritance, mixins |
| HTTP method handling | Manual if/else | हर HTTP verb का अलग method |
# Function-based view (FBV)
from django.http import HttpResponse
from django.shortcuts import render, get_object_or_404
def book_detail(request, pk):
book = get_object_or_404(Book, pk=pk)
if request.method == 'POST':
pass
return render(request, 'book_detail.html', {'book': book})
# Class-based view (CBV)
from django.views import View
class BookDetailView(View):
def get(self, request, pk):
book = get_object_or_404(Book, pk=pk)
return render(request, 'book_detail.html', {'book': book})
def post(self, request, pk):
pass
# urls.py
from django.urls import path
from . import views
urlpatterns = [
path('books/<int:pk>/', views.book_detail, name='book-detail-fbv'),
path('books-cbv/<int:pk>/', views.BookDetailView.as_view(), name='book-detail-cbv'),
]
# Generic CBV
from django.views.generic import DetailView
class BookDetailGeneric(DetailView):
model = Book
template_name = 'book_detail.html'Was this answer clear?