I am converting a set of existing APIs from tastypie to REST framework. By default when doing list APIs, tastypie returns a dictionary containing the list of objects and a dictionary of metadata, where REST framework just returns an array of objects. For example, I have a model called Site. Tastypie returns a dictionary that looks like
{ "meta": { ... some data here ...}, "site": [ {... first site...}, {...second site...} ... ] }
where REST framework returns just the array
[ {... first site...}, {...second site...} ... ]
We are not using the metadata from tastypie in any way. What is the least invasive way to change the return value in REST framework? I could override list(), but I would rather have REST framework do its thing where ever possible.
I think you will have to override the list()
method.
We first get the original response. Then we set the custom representation on response using data
attribute and return response with this custom representation.
class MyModelViewSet(viewsets.ModelViewSet):
def list(self, request, *args, **kwargs):
response = super(MyModelViewSet, self).list(request, *args, **kwargs) # call the original 'list'
response.data = {"site": response.data} # customize the response data
return response # return response with this custom representation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With