There are two approaches to specify the serializer class:
- First approach is to set the
serializer_class
attribute in your class.
- Second approach is to override the
get_serializer_class()
method.
If you already added the serializer_class
attribute in your class (first approach) then the get_serializer_class()
is definitely useless.
This is the example:
from django.contrib.auth.models import User
from myapp.serializers import UserSerializer
from rest_framework import generics
class UserList(generics.GenericAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
In most situations you should use the first approach because usually you will need only one serializer for your API view. Second approach is useful for dynamic behavior, such as using different serializers for read and write operations, or providing different serializers to different types of users.
Example:
def get_serializer_class(self):
if self.request.user.is_staff:
return StaffSerializer
return BasicSerializer