Mastering CRUD with Just 3 Lines: Introduction to ViewSet in Django REST Framework

Mastering CRUD with Just 3 Lines: Introduction to ViewSet in Django REST Framework

We used this simple setup for CRUD:

class ArticleListCreateView(generics.ListCreateAPIView):
    queryset = models.Article.objects.all()
    serializer_class = serializers.ArticleSerializer

class ArticleDetailView(generics.RetrieveUpdateDestroyAPIView):
    queryset = models.Article.objects.all()
    serializer_class = serializers.ArticleSerializer

Pretty cool, right? Just 6 lines and you have a full CRUD API.


Now, let me show you something even more powerful — ViewSets. With ModelViewSet, you can achieve the same functionality in only 3 lines. Sounds like magic? Let’s see.

We’re using the same project as the previous story. Feel free to clone it from my GitHub:
🔗 https://github.com/ArRosid/learn-def


🔧 Step 1: Update views.py

from rest_framework import viewsets
from . import models, serializers

class ArticleViewSet(viewsets.ModelViewSet):
    serializer_class = serializers.ArticleSerializer
    queryset = models.Article.objects.all()

Boom! That’s it. You now have a complete CRUD setup.


🔗 Step 2: Update urls.py

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

router = DefaultRouter()
router.register(r"article", views.ArticleViewSet)

urlpatterns = [
    path("", include(router.urls)),
]

🚀 Step 3: Run the Project

$ python manage.py runserver

Visit http://127.0.0.1:8000/article/ In your browser. You can create, retrieve, update, and delete articles from a beautiful browsable API — all with just 3 lines of code in the view.


🧪 Try it out:

  • Create a new article
  • View article details
  • Update the article
  • Delete the article

Convinced now? 😉


With ViewSets and routers, Django REST Framework lets you build fast, clean, and efficient APIs. Stay tuned — in the next post, we’ll explore even more powerful tools DRF has to offer.


Leave a Reply

Your email address will not be published. Required fields are marked *