Django — ViewSets
Basic ViewSet
from rest_framework import viewsets
from .models import Post
from .serializers import PostSerializer
class PostViewSet(viewsets.ModelViewSet):
queryset = Post.objects.all()
serializer_class = PostSerializer
ViewSet Actions
| Action | Method | Description |
|---|---|---|
| list | GET | List all |
| create | POST | Create one |
| retrieve | GET | Get one |
| update | PUT | Update one |
| partial_update | PATCH | Partial update |
| destroy | DELETE | Delete one |
Custom Actions
from rest_framework.decorators import action
from rest_framework.response import Response
class PostViewSet(viewsets.ModelViewSet):
queryset = Post.objects.all()
serializer_class = PostSerializer
@action(detail=False, methods=['get'])
def published(self, request):
posts = Post.objects.filter(published=True)
serializer = self.get_serializer(posts, many=True)
return Response(serializer.data)
Router
# urls.py
from rest_framework.routers import DefaultRouter
from .views import PostViewSet
router = DefaultRouter()
router.register(r'posts', PostViewSet)
urlpatterns = [
path('api/', include(router.urls)),
]
Generated Endpoints
GET /api/posts/ # List
POST /api/posts/ # Create
GET /api/posts/{id}/ # Retrieve
PUT /api/posts/{id}/ # Update
DELETE /api/posts/{id}/ # Delete
GET /api/posts/published/ # Custom action
Mini Practice
- Create a basic ViewSet
- Add custom actions
- Set up router
- Test all endpoints
Up Next
Continue with Permissions — API access control.
Related Topics
Frequently Asked Questions about ViewSets
What is ViewSets in Django?
ViewSets is a fundamental concept in Django. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn ViewSets?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn ViewSets.
Why is ViewSets important in Django?
ViewSets is essential for Django development. Understanding this concept will help you write better code and solve real-world problems more effectively.