0
0
DjangoHow-ToBeginner · 4 min read

How to Use Generic Views in DRF in Django: Simple Guide

In Django REST Framework, use generic views like ListCreateAPIView or RetrieveUpdateDestroyAPIView to quickly create API endpoints with common behaviors. These views handle standard operations like listing, creating, retrieving, updating, and deleting data with minimal code by specifying a queryset and a serializer_class.
📐

Syntax

Generic views in DRF are classes you inherit from to get common API behaviors. You usually set two main attributes:

  • queryset: The data you want to work with.
  • serializer_class: The serializer that converts data to and from JSON.

You pick a generic view class based on the API action you want, like listing or updating.

python
from rest_framework import generics
from .models import Item
from .serializers import ItemSerializer

class ItemListCreateView(generics.ListCreateAPIView):
    queryset = Item.objects.all()
    serializer_class = ItemSerializer
💻

Example

This example shows a simple API for a model called Item. It supports listing all items and creating new ones using ListCreateAPIView. The view automatically handles GET and POST requests.

python
from django.db import models
from rest_framework import serializers, generics

# Model
class Item(models.Model):
    name = models.CharField(max_length=100)
    description = models.TextField(blank=True)

# Serializer
class ItemSerializer(serializers.ModelSerializer):
    class Meta:
        model = Item
        fields = ['id', 'name', 'description']

# View
class ItemListCreateView(generics.ListCreateAPIView):
    queryset = Item.objects.all()
    serializer_class = ItemSerializer

# URL (in urls.py)
from django.urls import path

urlpatterns = [
    path('items/', ItemListCreateView.as_view(), name='item-list-create'),
]
Output
GET /items/ returns JSON list of items POST /items/ with JSON creates a new item and returns it
⚠️

Common Pitfalls

Common mistakes when using generic views include:

  • Not setting queryset or serializer_class, which causes errors.
  • Using the wrong generic view for your needs (e.g., using ListAPIView when you want to create items).
  • Not overriding methods when custom behavior is needed.
  • Forgetting to add the view to urls.py with .as_view().

Always check that your serializer and model fields match your API requirements.

python
from rest_framework import generics

# Wrong: missing serializer_class
class WrongView(generics.ListCreateAPIView):
    queryset = Item.objects.all()

# Right:
class RightView(generics.ListCreateAPIView):
    queryset = Item.objects.all()
    serializer_class = ItemSerializer
📊

Quick Reference

Generic ViewPurposeHTTP Methods Supported
ListAPIViewList all objectsGET
CreateAPIViewCreate a new objectPOST
RetrieveAPIViewRetrieve a single objectGET
UpdateAPIViewUpdate an objectPUT, PATCH
DestroyAPIViewDelete an objectDELETE
ListCreateAPIViewList and create objectsGET, POST
RetrieveUpdateAPIViewRetrieve and update an objectGET, PUT, PATCH
RetrieveDestroyAPIViewRetrieve and delete an objectGET, DELETE
RetrieveUpdateDestroyAPIViewRetrieve, update, and delete an objectGET, PUT, PATCH, DELETE

Key Takeaways

Use DRF generic views to quickly build standard API endpoints with minimal code.
Always set both queryset and serializer_class in your generic views.
Choose the generic view class that matches the HTTP methods your API needs.
Remember to add your generic view to urls.py using .as_view() for routing.
Override generic view methods only when you need custom behavior beyond defaults.