Views and ViewSets

Views & ViewSets in Django REST Framework (DRF):

In this section, we will learn how to connect our data (Models) with our APIs using Views and ViewSets in Django REST Framework.

What are Views in DRF?

In Django Rest Framework, Views are the parts of your application that handle the HTTP requests and return HTTP responses.
They decide “what to do when someone hits an API endpoint.”

In simpler words — when someone visits your API (like /api/books/), Views control what should happen next: fetch data, save new data, delete something, etc.

Types of Views in Django Rest Framework (DRF)

Django Rest Framework (DRF) provides several different ways to create Views — which are responsible for handling requests and sending responses in your API.Let’s understand each type of view in detail.

1. Function-Based Views (FBV)

These views are written just like regular Python functions.
They are simple to write and easy to understand, especially for beginners.

  • Think of FBVs as the most basic way to handle API logic.
  • You define a Python function and manually handle different HTTP methods like GET, POST, PUT, or DELETE.

Why use FBV?

  • Great for small projects or when you’re just starting with DRF.
  • Gives you full control over the logic of each HTTP method.

Example:
You write one function and check conditions like:

if request.method == ‘GET’:

    # return data

elif request.method == ‘POST’:

    # create new data

2. Class-Based Views (CBV)

These views are written using Python classes instead of functions.
Django Rest Framework automatically maps HTTP methods like GET, POST, etc., to specific methods in the class (like get(), post() etc.).

  • CBVs help you organize your code better.
  • You can also reuse code easily by using inheritance and mixins.

Why use CBV?

  • Better structure, especially for medium to large projects.
  • Makes code more organized and reusable.

Example: You define a class like BookListView and inside it define methods like:

def get(self, request):

    # return list of books

 

def post(self, request):

    # add a new book

3. Generic Views & ViewSets

DRF also provides Generic Views and ViewSets, which are powerful tools to reduce repetitive code.

Generic Views:

  • DRF offers pre-built generic classes like ListAPIView, CreateAPIView, RetrieveAPIView, etc.
  • You only need to specify which model to use and which serializer to use — and DRF handles the rest!

 ViewSets:

  • ViewSets are an advanced version of Generic Views.
  • They are designed to handle all CRUD operations (Create, Read, Update, Delete) in a single class — with even less code!
  • Instead of writing separate views for each operation, one ViewSet class can manage everything.

Why use Generic Views or ViewSets?

  • Helps you save time and write less code.
  • Ideal for large applications where you want to build APIs fast.
  • Cleaner, simpler, and more maintainable.

Example: A single BookViewSet class can handle listing, creating, updating, retrieving, and deleting books — without writing individual methods for each.

Let's Learn with Code – views.py

Now let’s understand how we use ViewSets with a real example.

# books/views.py

from rest_framework import viewsets

from .models import Book

from .serializers import BookSerializer

from rest_framework.permissions import IsAuthenticatedOrReadOnly

class BookViewSet(viewsets.ModelViewSet):

    queryset = Book.objects.all()

    serializer_class = BookSerializer

    permission_classes = [IsAuthenticatedOrReadOnly]

Explanation:

from rest_framework import viewsets

This line imports viewsets module from Django Rest Framework.
It allows us to create a ViewSet, which can automatically handle all CRUD operations — Create, Read, Update, Delete.

from .models import Book

This line imports the Book model that we created earlier in models.py.
This model represents the database table where our book records are stored.

from .serializers import BookSerializer

Here, we are importing the BookSerializer that we created earlier in serializers.py.
Serializers help in converting model data into JSON format (and vice versa).

from rest_framework.permissions import IsAuthenticatedOrReadOnly

This imports a permission class provided by DRF.
It means:

  • If the user is logged in, they can do everything (Create, Update, Delete).
  • If the user is not logged in, they can only read data (view the list or details).

class BookViewSet(viewsets.ModelViewSet):

 Here we create a class called BookViewSet, which inherits from ModelViewSet.
This is a powerful class that provides all CRUD operations automatically — without writing separate functions.

   queryset = Book.objects.all()

This line tells the ViewSet to fetch all records of Book model from the database.
It acts as the data source for our API.

   serializer_class = BookSerializer

This line tells DRF to use BookSerializer to convert data into JSON (when sending to frontend) and convert JSON into model data (when receiving from frontend).

   permission_classes = [IsAuthenticatedOrReadOnly]

This line applies the permissions.

  • Logged-in users can do all actions.
  • Non-logged-in users can only view the data.

Summary:

ViewSet:Handles all API operations in one class

queryset:Decides what data to work with

serializer_class:Tells which serializer to use

permission_classes:Controls who can access the API

Why is ViewSet Useful?

  • You don’t need to write CreateView, ListView, DeleteView separately.
  • Everything comes built-in.
  • Less code, more power!

What You’ll Learn from This Section:

  • How DRF handles HTTP requests behind the scenes.
  • How easy it is to build powerful APIs using ViewSets.
  • How to use permissions to control access

Exercise:

  • Create a StudentViewSet using ModelViewSet.

  • Test all CRUD operations using Postman:

    • Create student.

    • Read all students.

    • Update a student.

    • Delete a student.

Course Video in English