This is the response from Django when making axios api call in the frontend (array of JSON objects).
[
{
"id": 1,
"title": "How to create a django-react app",
"body": "You should first do this stuff and that"
},
{
"id": 5,
"title": "How to connect django with react",
"body": "Get this and that stuff"
}
]
But this is the response that I want (JSON object of JSON objects).
Is a Python dictionary the same as a Javascript object or Hashmap?
Is there some kind of middleware I can use to convert the shape?
Is this a job that the serializers.py needs to do or the views.py? How can I change the response from an array of objects to an object or objects?
{
1: {
"id": 1,
"title": "How to create a django-react app",
"body": "You should first do this stuff and that"
},
5: {
"id": 5,
"title": "How to connect django with react",
"body": "Get this and that stuff"
}
}
serializers.py
class ArticleSerializer(serializers.ModelSerializer):
class Meta:
model = Article
fields = '__all__'
views.py
class ArticleViewSet(ViewSet):
queryset = Article.objects.all()
def list(self, request):
serializer = ArticleSerializer(ArticleViewSet.queryset, many=True)
return Response(serializer.data)
def retrieve(self, request, pk=None):
article = get_object_or_404(ArticleViewSet.queryset, pk=pk)
serializer = ArticleSerializer(article, many=False)
return Response(serializer.data)