-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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