I am very new to django rest framework and I have to customize modelviewsets and serializes to return response only success message instead of queryset when put method was called on .
1 Answer
You can override the ModelViewSet response to do this. I am assuming this is only in case of a PUT request. Then you can do this:
class MyModelViewSet(ModelViewSet):
def update(self, request, *args, **kwargs):
super(MyModelViewSet, self).update(request, *args, **kwargs)
return Response({"status": "Success"}) # Your override
This is the original code for def update:
def update(self, request, *args, **kwargs):
partial = kwargs.pop('partial', False)
instance = self.get_object()
serializer = self.get_serializer(instance, data=request.data, partial=partial)
serializer.is_valid(raise_exception=True)
self.perform_update(serializer)
if getattr(instance, '_prefetched_objects_cache', None):
# If 'prefetch_related' has been applied to a queryset, we need to
# forcibly invalidate the prefetch cache on the instance.
instance._prefetched_objects_cache = {}
return Response(serializer.data) # This is the original code
You can find it in the UpdateModelMixin in DRF
2 Comments
Shibu Addi
Thanks ... Exactly what I was looking for.
rtindru
You're welcome; please accept the answer if your query is resolved