Viewsets and Routers in Django

 Viewsets and Routers in Django


DRF also includes viewsets and routers that can simplify the process of defining views and URL patterns.


Here's an example viewset for a Book model:


python

Copy code

from rest_framework import viewsets

from .models import Book

from .serializers import BookSerializer


class BookViewSet(viewsets.ModelViewSet):

    queryset = Book.objects.all()

    serializer_class = BookSerializer

In this example, we define a BookViewSet class that inherits from DRF's ModelViewSet. This provides a set of default views for CRUD operations on the Book model.


We can use a router to automatically generate URL patterns for our viewset:


python


from rest_framework import routers

from .views import BookViewSet


router = routers.SimpleRouter()

router.register(r'books', BookViewSet)


urlpatterns = router.urls

This sets up URL patterns for the BookViewSet viewset. The r'books' argument specifies the base URL for the viewset.

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...