Skip to main content

Django Rest Framework : Class Based Views-Generic Views

 Django REST Framework Views - Generic Views 

Class based views - Django Rest Framework

Django REST framework provides a set of generic views that you can use to quickly build API views. These views are designed to provide common behavior, such as allowing read-only or authenticated access to API endpoints.

Django's generic views... were developed as a shortcut for common usage patterns... They take certain common idioms and patterns found in view development and abstract them so that you can quickly write common views of data without having to repeat yourself.

Here is a list of the generic views provided by Django REST framework:

  • APIView: A base class for all other generic views. It provides the core implementation for handling requests and responses, and can be subclassed to create your own views.

  • CreateAPIView: A view for creating a new instance of a model. It handles the POST request and provides a default implementation for saving the new object to the database.

  • ListAPIView: A view for listing a queryset of objects. It handles the GET request and provides a default implementation for pagination and filtering.

  • RetrieveAPIView: A view for retrieving a single instance of a model. It handles the GET request and provides a default implementation for looking up the object by its primary key.

  • UpdateAPIView: A view for updating an instance of a model. It handles the PUT or PATCH request and provides a default implementation for saving the updated object to the database.

  • DestroyAPIView: A view for deleting an instance of a model. It handles the DELETE request and provides a default implementation for deleting the object from the database.

Certainly! Here are examples of using all of the generic views provided by Django REST framework:
from rest_framework.generics import ( APIView, CreateAPIView, ListAPIView, RetrieveAPIView, UpdateAPIView, DestroyAPIView ) from .models import Person from .serializers import PersonSerializer class PersonListView(ListAPIView): queryset = Person.objects.all() serializer_class = PersonSerializer class PersonCreateView(CreateAPIView): queryset = Person.objects.all() serializer_class = PersonSerializer class PersonDetailView(RetrieveAPIView): queryset = Person.objects.all() serializer_class = PersonSerializer class PersonUpdateView(UpdateAPIView): queryset = Person.objects.all() serializer_class = PersonSerializer class PersonDestroyView(DestroyAPIView): queryset = Person.objects.all() serializer_class = PersonSerializer

The PersonListView will handle a GET request to the /people/ endpoint and return a list of all Person objects in the database.

The PersonCreateView will handle a POST request to the /people/ endpoint and create a new Person object in the database.

The PersonDetailView will handle a GET request to the /people/<pk>/ endpoint and return a single Person object, identified by its primary key (pk).

The PersonUpdateView will handle a PUT or PATCH request to the /people/<pk>/ endpoint and update the Person object identified by its primary key.

The PersonDestroyView will handle a DELETE request to the /people/<pk>/ endpoint and delete the Person object identified by its primary key.


Certainly! In addition to the generic views provided by Django REST framework, you can also create your own custom views by subclassing APIView and implementing the methods for handling different HTTP request methods (e.g. get, post, put, etc.).

Here is an example of a custom view that handles both GET and POST requests:

from rest_framework.response import Response from rest_framework.views import APIView from .models import Person from .serializers import PersonSerializer class CustomPersonView(APIView): def get(self, request): people = Person.objects.all() serializer = PersonSerializer(people, many=True) return Response(serializer.data) def post(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)

    def put(self, request, pk): person = self.get_object(pk) serializer = PersonSerializer(person, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


This view will handle a GET request to the /custom-people/ endpoint and return a list of all Person objects in the database, serialized using the PersonSerializer class. It will also handle a POST request to the same endpoint, creating a new Person object in the database with the data provided in the request.

The put method uses the PersonSerializer to validate and save the updated data to the database. If the serializer is valid, it returns the serialized data in the response. If the serializer is invalid, it returns an error response with a status code of 400 Bad Request.


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 ) ...