Bird
Raised Fist0
Djangoframework~10 mins

Generic views in DRF in Django - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Generic views in DRF
Request comes in
Generic View Class
Dispatch method
Determine HTTP method
GET
ListModelMixin or RetrieveModelMixin
POST
CreateModelMixin
PUT/PATCH
UpdateModelMixin
DELETE
DestroyModelMixin
Perform action
Serialize data
Return Response
The generic view receives a request, decides which HTTP method is called, uses the matching mixin to handle the action, serializes data, and sends back a response.
Execution Sample
Django
from rest_framework import viewsets

class BookViewSet(viewsets.ModelViewSet):
    queryset = Book.objects.all()
    serializer_class = BookSerializer
This code creates a view that lists all books on GET and creates a new book on POST.
Execution Table
StepHTTP MethodAction SelectedQueryset AccessedSerializer UsedResponse Type
1GETListModelMixin.list()Book.objects.all()BookSerializerList of books JSON
2POSTCreateModelMixin.create()Book.objects.all()BookSerializerCreated book JSON
3PUTUpdateModelMixin.update()Book.objects.all()BookSerializerUpdated book JSON
4DELETEDestroyModelMixin.destroy()Book.objects.all()BookSerializer204 No Content
5PATCHUpdateModelMixin.partial_update()Book.objects.all()BookSerializerPartially updated book JSON
6OPTIONSGenericAPIView.options()N/AN/AAllowed methods info
💡 Request handled by matching mixin method based on HTTP method, response returned.
Variable Tracker
VariableStartAfter GETAfter POSTAfter PUTAfter DELETEAfter PATCH
request.methodNoneGETPOSTPUTDELETEPATCH
actionNonelist()create()update()destroy()partial_update()
querysetNoneBook.objects.all()Book.objects.all()Book.objects.all()Book.objects.all()Book.objects.all()
serializerNoneBookSerializerBookSerializerBookSerializerBookSerializerBookSerializer
response.status_codeNone200 OK201 Created200 OK204 No Content200 OK
Key Moments - 3 Insights
Why does the same queryset get used for all HTTP methods?
The queryset is defined once in the generic view and reused by all mixin methods to access data consistently, as shown in execution_table rows 1-5.
How does the view know which method to call for each HTTP request?
The dispatch method checks request.method and calls the corresponding mixin method, as seen in the concept_flow and execution_table where each HTTP method maps to a specific action.
Why is the serializer class the same for all actions?
The serializer_class is set once in the view and used to convert data to/from JSON for all actions, ensuring consistent data format, as tracked in variable_tracker.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what response status code is returned after a DELETE request?
A201 Created
B204 No Content
C200 OK
D404 Not Found
💡 Hint
Check the response.status_code column for the DELETE row in execution_table.
At which step does the view use the CreateModelMixin?
AStep 2
BStep 1
CStep 4
DStep 5
💡 Hint
Look at the Action Selected column in execution_table for the POST method.
If the serializer_class was changed, which variable_tracker row would be affected?
Arequest.method
Baction
Cserializer
Dqueryset
💡 Hint
See which variable holds the serializer class in variable_tracker.
Concept Snapshot
Generic views in DRF simplify API views by combining mixins.
They handle common actions: list, create, retrieve, update, destroy.
You define queryset and serializer_class once.
HTTP methods map to mixin methods automatically.
This reduces code and keeps views clean.
Full Transcript
Generic views in Django REST Framework help you write less code by providing ready-made classes for common API actions. When a request comes in, the generic view checks the HTTP method like GET or POST. It then calls the matching mixin method such as list() for GET or create() for POST. The view uses the queryset you set to get data and the serializer_class to convert data to JSON. Finally, it sends back the response. This flow makes building APIs faster and easier because you don't write repetitive code for each action.

Practice

(1/5)
1. What is the main purpose of using generic views in Django REST Framework (DRF)?
easy
A. To provide ready-made classes that simplify common API tasks like CRUD operations
B. To write raw SQL queries directly in views
C. To handle user authentication manually
D. To create HTML templates for the frontend

Solution

  1. Step 1: Understand generic views role

    Generic views in DRF offer pre-built classes to handle common API tasks such as listing, creating, updating, and deleting data.
  2. Step 2: Compare options

    Options B, C, and D describe unrelated tasks: raw SQL, manual auth, and frontend templates, which are not the main purpose of generic views.
  3. Final Answer:

    To provide ready-made classes that simplify common API tasks like CRUD operations -> Option A
  4. Quick Check:

    Generic views simplify CRUD = A [OK]
Hint: Generic views = ready-made CRUD classes in DRF [OK]
Common Mistakes:
  • Confusing generic views with authentication classes
  • Thinking generic views handle frontend rendering
  • Assuming generic views require manual SQL
2. Which of the following is the correct way to use a generic view to list all objects of a model named Book in DRF?
easy
A. class BookList(generics.ListAPIView):\n queryset = Book.objects.all()\n serializer_class = BookSerializer
B. class BookList(generics.CreateAPIView):\n queryset = Book.objects.all()\n serializer_class = BookSerializer
C. class BookList(generics.UpdateAPIView):\n queryset = Book.objects.all()\n serializer_class = BookSerializer
D. class BookList(generics.DestroyAPIView):\n queryset = Book.objects.all()\n serializer_class = BookSerializer

Solution

  1. Step 1: Identify the generic view for listing objects

    The ListAPIView is designed to list all objects of a model.
  2. Step 2: Match the class with the task

    Options B, C, and D correspond to creating, updating, and deleting respectively, which do not list objects.
  3. Final Answer:

    class BookList(generics.ListAPIView):\n queryset = Book.objects.all()\n serializer_class = BookSerializer -> Option A
  4. Quick Check:

    List all objects = ListAPIView = A [OK]
Hint: List objects use ListAPIView class [OK]
Common Mistakes:
  • Using CreateAPIView for listing data
  • Confusing UpdateAPIView with ListAPIView
  • Forgetting to set queryset or serializer_class
3. Given this DRF generic view code, what will be the HTTP method supported and the main action performed?
class ArticleDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = Article.objects.all()
    serializer_class = ArticleSerializer
medium
A. Supports only POST method to create a new article
B. Supports GET, PUT, PATCH, DELETE methods to retrieve, update, or delete an article
C. Supports GET method to list all articles
D. Supports DELETE method only to remove all articles

Solution

  1. Step 1: Understand RetrieveUpdateDestroyAPIView

    This generic view supports retrieving a single object (GET), updating it (PUT/PATCH), and deleting it (DELETE).
  2. Step 2: Match HTTP methods to actions

    Supports GET, PUT, PATCH, DELETE methods to retrieve, update, or delete an article correctly describes the supported methods (GET for retrieve, PUT/PATCH for update, DELETE for destroy) for a single article. Options A, C, and D describe incorrect methods or actions.
  3. Final Answer:

    Supports GET, PUT, PATCH, DELETE methods to retrieve, update, or delete an article -> Option B
  4. Quick Check:

    RetrieveUpdateDestroyAPIView = GET, PUT/PATCH, DELETE [OK]
Hint: RetrieveUpdateDestroyAPIView handles GET, PUT/PATCH, DELETE [OK]
Common Mistakes:
  • Thinking it supports POST for creation
  • Confusing list view with detail view
  • Assuming it deletes all objects instead of one
4. Identify the error in this DRF generic view code snippet:
class UserCreate(generics.CreateAPIView):
    serializer_class = UserSerializer
medium
A. CreateAPIView does not exist in DRF
B. serializer_class should be named serializer
C. Class name should be lowercase
D. Missing queryset attribute causes runtime error

Solution

  1. Step 1: Check required attributes for CreateAPIView

    While CreateAPIView requires serializer_class, it also typically needs a queryset attribute to function properly without errors, especially in standard setups with permissions.
  2. Step 2: Identify the error

    The missing queryset attribute causes runtime errors in many scenarios. Options A, B, and D are incorrect: CreateAPIView does exist (A), serializer_class is the correct name (B), and class names should use PascalCase (D).
  3. Final Answer:

    Missing queryset attribute causes runtime error -> Option D
  4. Quick Check:

    Missing queryset = runtime error [OK]
Hint: Always set queryset with generic views unless serializer handles all [OK]
Common Mistakes:
  • Omitting queryset attribute
  • Renaming serializer_class incorrectly
  • Thinking CreateAPIView is invalid
  • Using lowercase class names
5. You want to create a DRF API endpoint that allows listing all Product items and creating new ones in the same view. Which generic view class should you use and why?
hard
A. Use generics.ListAPIView only because creation should be separate
B. Use generics.RetrieveUpdateDestroyAPIView because it handles all CRUD operations
C. Use generics.ListCreateAPIView because it supports both listing and creating in one view
D. Use generics.CreateAPIView only because listing is not needed

Solution

  1. Step 1: Identify the requirement

    The endpoint must list all products and allow creating new ones in the same view.
  2. Step 2: Match generic view to requirement

    ListCreateAPIView is the correct choice as it supports GET (listing) and POST (creating). Use generics.RetrieveUpdateDestroyAPIView because it handles all CRUD operations (RetrieveUpdateDestroyAPIView) is for single-object detail operations. Options A and C support only a single action each.
  3. Final Answer:

    Use generics.ListCreateAPIView because it supports both listing and creating in one view -> Option C
  4. Quick Check:

    List + Create = ListCreateAPIView [OK]
Hint: ListCreateAPIView combines list and create in one view [OK]
Common Mistakes:
  • Using RetrieveUpdateDestroyAPIView for list/create
  • Choosing only CreateAPIView or ListAPIView alone
  • Not combining actions in one view