Django Rest Framework ViewSet CRUD Operation with Example

Django ViewSets provide a powerful and efficient way to implement CRUD (Create, Read, Update, Delete) operations in your Django web applications. They streamline the process of building API endpoints by consolidating related functionality into a single class. In this blog post, we will explore Django ViewSets and walk through examples of how to perform CRUD operations using them.

What Are Django ViewSets?

A Django ViewSet is a class-based view that combines the logic for multiple related views into a single class. They are particularly useful when building RESTful APIs as they provide a way to organize and manage your API endpoints. ViewSets are built on top of Django’s class-based views and are designed to work seamlessly with Django Rest Framework (DRF).

Step by Step Implementation

Lets create a Task CRUD operation using Django Viewset..

Setting Up Your Environment

Before diving into examples, make sure you have Django and DRF installed in your environment. You can install them using pip:

pip install django djangorestframework

Once you have them installed, create a Django project and an app if you haven’t already:

django-admin startproject myproject
cd myproject
python startapp myapp

Step 1: Creating a Model

For our examples, we’ll create a simple model named “Task” in the myapp/ file:

from django.db import models

class Task(models.Model):
    title = models.CharField(max_length=100)
    description = models.TextField()
    completed = models.BooleanField(default=False)

    def __str__(self):
        return self.title

Don’t forget to run migrations to create the database table for the Task model:

python makemigrations
python migrate

Step 2: Implementing CRUD Operations with Django ViewSets

Now, let’s create a ViewSet for the Task model to perform CRUD operations:

# myapp/
from rest_framework import viewsets
from .models import Task
from .serializers import TaskSerializer

class TaskViewSet(viewsets.ModelViewSet):
    queryset = Task.objects.all()
    serializer_class = TaskSerializer

Step 3: Serializers

To handle data serialization and deserialization, create a serializer class in myapp/

from rest_framework import serializers
from .models import Task

class TaskSerializer(serializers.ModelSerializer):
    class Meta:
        model = Task
        fields = '__all__'

Learn More about How to Serializer and Deserializer in Django Rest Framework with Examples

Step 4: Configuring URLs

Now, let’s configure the URLs for our ViewSet in myproject/

from django.urls import path, include
from rest_framework.routers import DefaultRouter
from myapp.views import TaskViewSet

router = DefaultRouter()
router.register(r'tasks', TaskViewSet)

urlpatterns = [
    path('', include(router.urls)),

Step 5: Testing CRUD Operations

With everything set up, you can now test your CRUD operations using Django’s admin interface or API testing tools like Postman or curl. Here’s how you can perform basic CRUD operations:

  1. Create a Task (POST): Send a POST request to http://localhost:8000/tasks/ with JSON data like this:
curl -X POST http://localhost:8000/tasks/ -H "Content-Type: application/json" -d '{
    "title": "Finish Blog Post",
    "description": "Write a blog post about Django ViewSets.",
    "completed": false
  1. Retrieve Tasks (GET): Send a GET request to http://localhost:8000/tasks/ to retrieve a list of all tasks. – curl http://localhost:8000/tasks/
  2. Retrieve a Task by ID (GET): Send a GET request to http://localhost:8000/tasks/{task_id}/ to retrieve a specific task by its ID. – curl http://localhost:8000/tasks/{task_id}/
  3. Delete a Task (DELETE): Send a DELETE request to http://localhost:8000/tasks/{task_id}/ to delete a specific task by its ID. – curl -X DELETE http://localhost:8000/tasks/{task_id}/
  4. Update a Task (PUT): Send a PUT request to http://localhost:8000/tasks/{task_id}/ with updated JSON data.
curl -X PUT http://localhost:8000/tasks/{task_id}/ -H "Content-Type: application/json" -d '{
    "title": "Updated Blog Post",
    "description": "Updated blog post content.",
    "completed": true


Django ViewSets provide an elegant and efficient way to implement CRUD operations in your Django applicationss By consolidating related functionality into a single class, you can create clean and maintainable API endpoints. In this blog post, we’ve covered the basics of creating and using Django ViewSets to perform CRUD operations, making your API development process smoother and more organized.

Find this project on Github.

Blogs You Might Like to Read!