Skip to main content

Django REST Framework Views - ViewSets

Django Rest Framework ViewSets

ViewSets - Django REST framework 

In Django REST framework, a ViewSet is a class that defines the actions that can be performed on a particular model or resource. A ViewSet is typically paired with a Router, which maps the HTTP methods and URL patterns to the appropriate ViewSet actions.

Django REST framework provides several built-in ViewSet classes, including:

  • ViewSet: A base class for all other ViewSet classes. It provides a basic implementation for handling requests and responses, and can be subclassed to create your own ViewSet classes.


  • ModelViewSet: A ViewSet for working with a model and its related serializer. It provides the default implementation for the following actions: list, create, retrieve, update, and destroy.


  • ReadOnlyModelViewSet: A ViewSet that provides read-only actions for a model and its related serializer. It provides the default implementation for the following actions: list and retrieve.


  • GenericViewSet: A ViewSet that allows you to define custom actions by mixing and matching different mixins.

Here is an example of using the ModelViewSet to create a PersonViewSet that provides the default implementation for the list, create, retrieve, update, and destroy actions:

from rest_framework.viewsets import ModelViewSet from .models import Person from .serializers import PersonSerializer class PersonViewSet(ModelViewSet): queryset = Person.objects.all() serializer_class = PersonSerializer

This ViewSet will handle the following HTTP methods and URL patterns:

  • GET /people/: List all Person objects.
  • POST /people/: Create a new Person object.
  • GET /people/<pk>/: Retrieve a single Person object identified by its primary key (pk).
  • PUT /people/<pk>/ or PATCH /people/<pk>/: Update a Person object identified by its primary key.
  • DELETE /people/<pk>/: Delete a Person object identified by its primary key.
Certainly! Here are examples of using the other built-in ViewSet classes provided by Django REST framework:

from rest_framework.viewsets import ReadOnlyModelViewSet, ViewSet, GenericViewSet from .models import Person from .serializers import PersonSerializer class ReadOnlyPersonViewSet(ReadOnlyModelViewSet): queryset = Person.objects.all() serializer_class = PersonSerializer class CustomPersonViewSet(ViewSet): def list(self, request): people = Person.objects.all() serializer = PersonSerializer(people, many=True) return Response(serializer.data) def create(self, request): serializer = PersonSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class MixinPersonViewSet(ListModelMixin, CreateModelMixin, GenericViewSet): queryset = Person.objects.all() serializer_class = PersonSerializer

The CustomViewSet is a ViewSet that defines a custom list action. It handles a GET request to the /custom-people/ endpoint and returns a list of all Person objects in the database, serialized using the PersonSerializer class.

The ReadOnlyPersonViewSet is a ReadOnlyModelViewSet that provides the default implementation for the list and retrieve actions. It will handle GET requests to the /read-only-people/ and /read-only-people/<pk>/ endpoints, allowing you to list and retrieve Person objects, but not create, update, or delete them.


You can also use mixins to create custom ViewSet classes that combine the behavior of multiple built-in ViewSet classes. For example, you might use the ListModelMixin, CreateModelMixin, RetrieveModelMixin, UpdateModelMixin, and DestroyModelMixin to create a ViewSet that provides the default implementation for all CRUD actions.

Certainly! Here are a few more points to consider when working with ViewSet classes in Django REST framework:

  • You can override the default behavior of a ViewSet by defining custom methods for the different actions. For example, you might want to define a custom create method that performs additional processing or validation on the data being created.

  • You can use ViewSet classes with a Router to automatically generate the URL patterns and wire them up to the appropriate actions. For example, you can use the DefaultRouter to automatically generate the URL patterns for a ViewSet and include them in your URLconf.

  • You can use the @action decorator to define custom actions on a ViewSet. These actions can be mapped to custom methods or to the built-in ViewSet actions (e.g. list, create, etc.).

Here is an example of using the @action decorator to define a custom action on a ViewSet:

from rest_framework.decorators import action from rest_framework.response import Response from .models import Person from .serializers import PersonSerializer class PersonViewSet(ViewSet): def list(self, request): people = Person.objects.all() serializer = PersonSerializer(people, many=True) return Response(serializer.data) @action(methods=['get'], detail=True) def greeting(self, request, pk=None): person = Person.objects.get(pk=pk) return Response(f"Hello, {person.name}!")


This ViewSet will handle a GET request to the /people/<pk>/greeting/ endpoint, returning a greeting for the Person object identified by its primary key.

I hope this helps! Let me know if you have any questions.

Comments

Favourite post

Part 2 : TCS DCA python coding questions

TCS wings1 DCA python coding TCS elevate wings1 coding questions This post contains only coding questions asked in TCS digital wings1 or tcs elevate wings1 exam. If anyone want coding answer of these questions please comment me or reach me through email provided. Given a string str which consists of only 3 letters representing the color,(H) Hue, (S) Saturation, (L) Lightness, called HSL colors. The task is to count the occurrence of ordered triplet “H, S, L” in a given string and give this count as the output. This question was asked in April 21 Digital Capababilty Assessment Examples: A) Input HHSL Output 2 Explanation : There are two triplets of RGB in the given string: H at index O, S at index 2 and Lat index 3 forms one triplet of HSL. H at index 1, S at index 2 and Lat index 3 forms the second triplet of HSL. B) Input:   SHL Output: 0 Explanation : No triplets exists. In this 3 Palindrome, Given an input string word, split the string into exactly 3 palindromic substrings. Work...

Part 1 : TCS DCA python coding questions

TCS wings1 DCA python coding TCS elevate wings1 coding questions This post contains only coding questions asked in TCS digital wings1 or tcs elevate wings1 exam. If anyone want coding answer of these questions please comment me or reach me through email provided. Find how many Sexy Prime Numbers in a given range k and p.  Sexy prime means the prime numbers that differ from each other by 6. Where difference between two sexy prime numbers is 6. Constraint: 2 <=p<k<= 1000,000,000. Sample Input: 4  40 Output: 7 Explanation: [5,11] [7,13] [11,17] [13,19] [17,23]  [23,29] [31,37] Problem Description -: Given two non-negative integers n1 and n2, where n1 For example: Suppose n1=11 and n2=15. There is the number 11, which has repeated digits, but 12, 13, 14 and 15 have no repeated digits. So, the output is 4. Example1: Input: 11 — Vlaue of n1 15 — value of n2 Output: 4 Example 2: Input: 101 — value of n1 200 — value of n2 Output: 72 Consider the string S1 = 321 All char...

Calculator program using python tkinter

Project Name:- Simple Calculator Software using Python Tkinter. Dependencies:-                           1)Install  Tkinter- https://www.techinfected.net/2015/09/how-to-install-and-use-tkinter-in-ubuntu-debian-linux-mint.html                                 2)Install Math Library- for python3- pip3 install math  for python2- pip install math  ******************************************//************************************************************************ from tkinter import * from math import * class cal: def press( self ,n): self .text.insert(INSERT,n) def dl( self ): self .text.delete( 1.0 , 2.0 ) def equal( self ): self .exp= self .text.get( 1.0 ,END) try : self .result= eval ( self .exp) self .text.delete( 1.0 , 2.0 ) ...