0
0
Djangoframework~5 mins

ViewSets and routers in Django

Choose your learning style9 modes available
Introduction

ViewSets and routers help you write less code to handle common web actions like showing, adding, or changing data.

When you want to create a simple API to list, create, update, or delete items.
When you want to avoid writing separate functions for each action in your web app.
When you want your URLs to be created automatically for common actions.
When you want to keep your code clean and organized by grouping related actions.
When you want to quickly build REST APIs without repeating code.
Syntax
Django
from rest_framework import viewsets
from rest_framework.routers import DefaultRouter

class MyModelViewSet(viewsets.ModelViewSet):
    queryset = MyModel.objects.all()
    serializer_class = MyModelSerializer

router = DefaultRouter()
router.register(r'mymodels', MyModelViewSet)

urlpatterns = router.urls

ViewSet: A class that groups common actions like list, create, update, delete.

Router: Automatically creates URL patterns for the ViewSet actions.

Examples
This ViewSet handles all CRUD actions for books.
Django
class BookViewSet(viewsets.ModelViewSet):
    queryset = Book.objects.all()
    serializer_class = BookSerializer
This router creates URLs like /books/, /books/{id}/ automatically.
Django
router = DefaultRouter()
router.register(r'books', BookViewSet)

urlpatterns = router.urls
This ViewSet only allows reading data (list and retrieve), no changes.
Django
class ReadOnlyBookViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = Book.objects.all()
    serializer_class = BookSerializer
Sample Program

This example shows a full setup for a simple API to manage fruits. You can list all fruits, add new ones, update, or delete them using the URLs created automatically.

Django
from django.urls import path, include
from rest_framework import viewsets
from rest_framework.routers import DefaultRouter
from rest_framework.serializers import ModelSerializer
from django.db import models

# Simple model
class Fruit(models.Model):
    name = models.CharField(max_length=100)

# Serializer for Fruit
class FruitSerializer(ModelSerializer):
    class Meta:
        model = Fruit
        fields = ['id', 'name']

# ViewSet for Fruit
class FruitViewSet(viewsets.ModelViewSet):
    queryset = Fruit.objects.all()
    serializer_class = FruitSerializer

# Router setup
router = DefaultRouter()
router.register(r'fruits', FruitViewSet)

# URL patterns
urlpatterns = [
    path('', include(router.urls)),
]

# Explanation:
# This code creates a Fruit model, serializer, and a ViewSet that handles all actions.
# The router automatically creates URLs like /fruits/ and /fruits/{id}/ for listing and detail.
OutputSuccess
Important Notes

Routers save time by creating URLs for you, so you don't write them manually.

ViewSets group related actions, making your code cleaner and easier to read.

You can customize which actions are allowed by choosing different ViewSet classes.

Summary

ViewSets group common web actions like list, create, update, and delete.

Routers automatically create URLs for these actions, saving you from writing URL code.

This combination helps you build clean and simple APIs quickly.