Add hook for response data in Create and Update mixins

Warning: This is to start a discussion and has not been tested.

Our use case for this is to remove a field from the output. The previous solutions also remove the field from the Browsable API after a PUT request!, where not consistent across POST and PUT requests, or increased boiler plate. But this could also be used to return a simple status message rather than an object or a more complex object.

Maybe the object should also be passed to the hooks? It might also be better to have one hook (Where to implement?) self.request.method could be used to distinguish between POST/PUT. The hooks could return the response instead, giving control over the status code and headers too.
This commit is contained in:
Simon Luijk 2014-01-02 11:41:21 +01:00
parent 2921455ea7
commit 76392635c4

View File

@ -53,7 +53,8 @@ class CreateModelMixin(object):
self.object = serializer.save(force_insert=True)
self.post_save(self.object, created=True)
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=status.HTTP_201_CREATED,
data = self.get_create_response_data(serializer)
return Response(data, status=status.HTTP_201_CREATED,
headers=headers)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
@ -64,6 +65,9 @@ class CreateModelMixin(object):
except (TypeError, KeyError):
return {}
def get_create_response_data(self, serializer):
return serializer.data
class ListModelMixin(object):
"""
@ -136,7 +140,8 @@ class UpdateModelMixin(object):
return Response(err.message_dict, status=status.HTTP_400_BAD_REQUEST)
self.object = serializer.save(**save_kwargs)
self.post_save(self.object, created=created)
return Response(serializer.data, status=success_status_code)
data = self.get_update_response_data(serializer)
return Response(data, status=success_status_code)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
@ -159,6 +164,9 @@ class UpdateModelMixin(object):
# return a 404 response.
raise
def get_update_response_data(self, serializer):
return serializer.data
def pre_save(self, obj):
"""
Set any attributes on the object that are implicit in the request.