Blog CRUD Application Using DRF — Viewsets
Django Rest Framework is a powerful tool that allows you to easily build RESTful APIs using Django. By defining your models, serializers, views, and URLs, you can quickly create a blog post application that allows users to create, read, update, and delete blog posts via a web API.
In Django Rest Framework, a ViewSet is a class-based view that provides a set of common actions (i.e., CRUD operations) for a specific model or queryset.
ViewSets allow you to define your API endpoints in a more concise and structured way, as they provide a set of default methods that handle common HTTP operations, such as GET, POST, PUT, PATCH, and DELETE.
There are two main types of ViewSets in Django Rest Framework: ModelViewSet and ReadOnlyModelViewSet.
The ModelViewSet is the most commonly used ViewSet, as it provides all the actions that are required to implement a full CRUD API. It includes methods such as list, create, retrieve, update, and destroy, which correspond to the HTTP GET, POST, GET (single object), PUT/PATCH, and DELETE methods, respectively.
You can also override these default methods to add custom behavior, such as filtering or authentication.
Today, We are going to check ModelViewSets
Create a django-project
I have create a project named "api".
Now, let create a new app called "books".
books app
# models.py
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=255)
author = models.CharField(max_length=150)
class Meta:
db_table = "Book"
def __str__(self):
return self.title
# serializers.py
from rest_framework import serializers
from .models import Book
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = '__all__'
# views.py
from rest_framework import viewsets
from .models import Book
from .serializers import BookSerializer
class BookViewSet(viewsets.ModelViewSet):
queryset = Book.objects.all()
serializer_class = BookSerializer
# urls.py
from rest_framework.routers import DefaultRouter
from django.urls import include, path
from .views import BookViewSet
router = DefaultRouter()
router.register(r'book_post', BookViewSet)
urlpatterns = [
path('', include(router.urls))
]
api project
# urls.py
from django.contrib import admin
from django.urls import path, include
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView
urlpatterns = [
path('admin/', admin.site.urls),
path('api/token/', TokenObtainPairView.as_view(), name="token_obtain_pair"),
path('api/token/refresh', TokenRefreshView.as_view(), name="token_refresh"),
# apps
path('api/blog/', include('apps.blogs.urls')),
path('api/member/', include('apps.privateapi.urls')),
path('api/books/', include('apps.books.urls')),
]