Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return dictionary instead of array in REST framework

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.

like image 409
Mad Wombat Avatar asked Oct 23 '15 15:10

Mad Wombat


1 Answers

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
like image 85
Rahul Gupta Avatar answered Oct 08 '22 01:10

Rahul Gupta