Skip to content

Instantly share code, notes, and snippets.

@fleepgeek
Forked from unpluggedcoder/views.py
Created June 24, 2019 15:42
Show Gist options
  • Save fleepgeek/b374b905d6ede28078bd3cac260c68bf to your computer and use it in GitHub Desktop.
Save fleepgeek/b374b905d6ede28078bd3cac260c68bf 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