3👍
You can return different serializers in different context, by overriding the get_serializer
method on GenericAPIView
or any of its subclasses.
Something like this would be about right…
def get_serializer(self, ...):
if self.request.accepted_renderer.format == 'api':
# Browsable style
else:
# Standard style
If you code that behaviour as a mixin class you’d then be able to easily reuse it throughout your views.
1👍
I created this mixin to use the serializer_class_api when in API mode:
class SerializerAPI(object):
def get_serializer_class(self, *args, **kwargs):
parent = super(SerializerAPI, self).get_serializer_class(*args, **kwargs)
if (hasattr(self.request, 'accepted_renderer') and
self.request.accepted_renderer.format == 'api'):
return self.serializer_class_api
else:
return parent
Source:stackexchange.com