Reputation: 205
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.
Upvotes: 2
Views: 1145
Reputation: 1
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
Upvotes: 0
Reputation: 597
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}
Upvotes: 3