2

I'm using Django REST framework to make an API.

For my serialized models I get a response looks like this:

[GET] http://12.0.0.1/0.5/barrios/?format=json

[
  {
    "name": "La Julia",
    "zone": 1
  },
  {
    "name": "La Floresta",
    "zone": 2
  }
]

But, what I want looks like this:

{
  "barrios": { 
    "barrio": [
      {
        "name": "La Julia",
        "zone": 1
      },
      {
        "name": "La Floresta",
        "zone": 2
      }
    ]
  }
}

Any thoughts?

1 Answer 1

3

You can override the list() method in your view to get the desired response.

class MyView(..):

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        serializer_data = serializer.data # get the default serialized representation
        custom_data = {'barrios': {'barrio': serializer_data}} # custom representation
        return Response(custom_data)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.