0
0
Djangoframework~3 mins

Why Generic views in DRF in Django? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how to stop repeating yourself and build APIs faster with less code!

The Scenario

Imagine building an API where you write separate code for listing, creating, updating, and deleting items for every model.

You have to repeat similar code again and again for each endpoint.

The Problem

Writing all these views manually is slow and boring.

It's easy to make mistakes or forget to handle some HTTP methods properly.

Maintaining and updating this repeated code becomes a headache as your project grows.

The Solution

Generic views in DRF provide ready-made classes that handle common API actions like list, create, update, and delete.

You just configure them with your model and serializer, and they do the heavy lifting for you.

Before vs After
Before
class BookList(APIView):
    def get(self, request):
        books = Book.objects.all()
        serializer = BookSerializer(books, many=True)
        return Response(serializer.data)
After
class BookList(generics.ListAPIView):
    queryset = Book.objects.all()
    serializer_class = BookSerializer
What It Enables

You can build clean, consistent, and maintainable APIs quickly without rewriting common logic.

Real Life Example

When creating a blog API, you can use generic views to handle posts and comments with minimal code, focusing on unique features instead of boilerplate.

Key Takeaways

Manual API views require repetitive code for common actions.

Generic views provide reusable classes for standard API operations.

This saves time, reduces errors, and makes your code easier to maintain.