Skip to content

Instantly share code, notes, and snippets.

@unpluggedcoder
Last active January 16, 2020 10:57
Show Gist options
  • Save unpluggedcoder/d0e57033d2729f0d69d4f4cfe6505846 to your computer and use it in GitHub Desktop.
Save unpluggedcoder/d0e57033d2729f0d69d4f4cfe6505846 to your computer and use it in GitHub Desktop.
Use corresponding serializer class for different request method in Django Rest Framework - Part 3
# views.py
from rest_framework import exceptions
from rest_framework import generics
from myapp import models
from myapp import serializers as ser
class MethodSerializerView(object):
'''
Utility class for get different serializer class by method.
For example:
method_serializer_classes = {
('GET', ): MyModelListViewSerializer,
('PUT', 'PATCH'): MyModelCreateUpdateSerializer
}
'''
method_serializer_classes = None
def get_serializer_class(self):
assert self.method_serializer_classes is not None, (
'Expected view %s should contain method_serializer_classes '
'to get right serializer class.' %
(self.__class__.__name__, )
)
for methods, serializer_cls in self.method_serializer_classes.items():
if self.request.method in methods:
return serializer_cls
raise exceptions.MethodNotAllowed(self.request.method)
class UsersListCreateView(MethodSerializerView, generics.ListCreateAPIView):
'''
API: /users
Method: GET/POST
'''
queryset = models.User.objects.all()
method_serializer_classes = {
('GET', ): ser.UserListViewSerializer,
('POST'): ser.UserCreateUpdateSerializer
}
class UsersDetailView(MethodSerializerView, generics.RetrieveUpdateAPIView):
'''
API: /user/:user_uuid
Method: GET/PUT/PATCH
'''
queryset = models.User.objects.all()
method_serializer_classes = {
('GET', ): ser.UserListViewSerializer,
('PUT', 'PATCH'): ser.UserCreateUpdateSerializer
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment