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