Home > OS >  In DRF, how to get dictionary format in JSON response rather than List of dcitionaries
In DRF, how to get dictionary format in JSON response rather than List of dcitionaries

Time:12-17

How to get dictionary format in JSON response rather than List of dictionaries. Right now am getting response like list of dictionaries and I want to get response without list.

#Response I get for example

[
    {
        "id": 40,
        "full_name": "Don Ser 1",
        "email": "[email protected]",
        "phone": 12345,
        "address_line_1": "sdsdsdsd",
        "address_line_2": "dsdsdsd",
   
    },
    {
        "id": 41,
        "full_name": "Don Ser 2",
        "email": "[email protected]",
        "phone": 121356456,
        "address_line_1": "sdsdsdsd",
        "address_line_2": "dsdsdsd",
    
    }
]

#Response I Like to get is without List.

[
    {
        "id": 40,
        "full_name": "Don Ser 1",
        "email": "[email protected]",
        "phone": 12345,
        "address_line_1": "sdsdsdsd",
        "address_line_2": "dsdsdsd",
     
    },
    {
        "id": 41,
        "full_name": "Don Ser 2",
        "email": "[email protected]",
        "phone": 121356456,
        "address_line_1": "sdsdsdsd",
        "address_line_2": "dsdsdsd",
  
    }
}

How do I achieve this? Additionally I like to know why it returned it in List rather than dictionary?

CodePudding user response:

If you are returning your response in DRF with serializer.data the simplest way to achieve that is:

return Response(serializer.data[0], status=status.HTTP_200_OK)

If you want to include the whole dictionary in another dictionary you'd have to give it a key so it would something like this:

return Response({"results":serializer.data[0]}, status=status.HTTP_200_OK)

Otherwise if you are using it on a simple item you can just specify it the way you want i.e. :

serializer = Serializer(data=request.data)
if serializer.is_valid():
    device = serializer.save()
    return Response({"pk": device.id}, status=status.HTTP_201_CREATED)

CodePudding user response:

If you want to return a dict you must define a structure, e.g.

{'results': [
 {
        "id": 40,
        "full_name": "Don Ser 1",
        "email": "[email protected]",
        "phone": 12345,
        "address_line_1": "sdsdsdsd",
        "address_line_2": "dsdsdsd",
     
    },
    {
        "id": 41,
        "full_name": "Don Ser 2",
        "email": "[email protected]",
        "phone": 121356456,
        "address_line_1": "sdsdsdsd",
        "address_line_2": "dsdsdsd",
  
    }
]}

But just return a dict without a key is not possible.

  • Related