3

Like mentioned in the title.I have such JSON array being returned from backend:

[
    {id:1, name:'name1'},
    {id:2, name:'name2'},
    {id:3, name:'name3'},
    {id:4, name:'name4'}
] 

and I would like to return something like this instead:

{
  "1": {id:1, name:'name1'},
  "2": {id:2, name:'name2'},
  "3": {id:3, name:'name3'},
  "4": {id:4, name:'name4')
}

Is it possible in Django Rest framework to send such object as Response ? Obviously there will not be too many keys so size should not be an issue.

2 Answers 2

3

You can modify the data before sending it to the client.

data = [
    {id:1, name:'name1'},
    {id:2, name:'name2'},
    {id:3, name:'name3'},
    {id:4, name:'name4'}
]

data = {key["id"]:value for value in data}
return JsonResponse(data)

Alternative If you are using serializer

If you are using serializer use to_representation to modify data while serializing it. It will have no performance impact on than the default representation.

class MySerializer(serializers.ModelSerializer):
    class Meta:
        model = MyModal
        fields = ('foo', 'bar', .....,)

    def to_representation(self, instance):
        row = super(MySerializer, self).to_representation(instance)
        return {row["id"]:row}
        
Sign up to request clarification or add additional context in comments.

3 Comments

How will that affect my perfomance in case the amount of the elements gets really big compared to default serializer data?
Good to know if you are using serializer, I have edited my answer for it. It won't impact performance.
This currently returns an array which contains the desired Object at first index instead of basicaly returning the object on it's own. @Suryaveer Singh
0

The way I solved it was by overriding the list() method in your viewset:

class YourViewSet(viewsets.ModelViewSet):
    queryset = YourModel.objects.all()
    serializer_class = YourSerializer

    def list(self, request, *args, **kwargs):  # Override list method to list the data as a dictionary instead of array
        response = super(YourViewSet, self).list(request, *args, **kwargs)  # Call the original 'list'
        response_dict = {}
        for item in response.data:
            idKey = item['id']  # Use id as key
            response_dict[idKey] = item
        response.data = response_dict  # Customize response data into dictionary with id as keys instead of using array
        return response  # Return response with this custom representation

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.