A default DRF resource is limited to accepting the same object it later returns. I want to use a different serializer for the input than the output. For example, I want to imp
My problem is that I want to have different serializers for input and output of a service.
It's easy enough to have different serializers for different request methods (eg something to response to GET requests that's different to PUT
, POST
etc...)
Just override get_serializer_class()
, and return a different serializer class depending on the value of self.request.method
.
That may not be exactly what you're looking for because when you PUT or POST data you'll still end up with the same output style as you supplied.
In that case you should probably just write the view explicitly rather than relying on the default generic views, something along these lines...
class UserCreateOrListView(views.APIView):
def get(self, request, *args, **kwargs):
serializer = ImaginaryUserOutputSerializer(User.objects.all())
return Response(serializer.data)
def post(self, request, *args, **kwargs):
serializer = ImaginaryUserInputSerializer(data=request.DATA)
if serializer.is_valid():
user = serializer.save()
output_serializer = ImaginaryUserOutputSerializer(user)
return Response(output_serializer.data)
else:
return Response(serializer.errors, 400)
etc...
It's also worth asking on the mailing list as other users may be doing something similar and have useful patterns to share.