3๐
โ
use get_serializer_class
function like this
class HelloApiView(APIView):
"""Test API View"""
serializer_class = serializers.HelloSerializer
def get_serializer_class(self):
if self.request.method == 'POST':
return YOUR_SERIALIZER_1
elif self.request.method == 'GET':
return YOUR_SERIALIZER_2
else:
return YOUR_DEFAULT_SERIALIZER
def get()
def post(self, request):
"""Create a hello message with our name"""
serializer = self.serializer_class(data=request.data)
if serializer.is_valid():
name = serializer.validated_data.get('name')
message = f'Hello {name}!'
return Response({'message': message})
else:
return Response(
serializer.errors,
status=status.HTTP_400_BAD_REQUEST
)
๐คMuhammad Hassan
1๐
This is quite simple to do, just overwrite the get_serializer_class
method to return the serializer class based on the request method.
class HelloApiView(APIView):
def get_serializer_class(self):
if self.request.method.lower() == "get":
return MyApiControllerGetSerializer
else:
return MyApiControllerSerializer
๐คTommaso Barbugli
- [Django]-Django external script ImportError: No module named Utils
- [Django]-When a Web framework isn't convenient to use?
- [Django]-How to replace all spaces, tabs, new lines, commas and underscores with dashes?
- [Django]-Django Generated polish plurals form in .po file not working
Source:stackexchange.com