1

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)

1 Answer 1

2

You should be able to build a dictionary in the ArticleViewSet's list method:

class ArticleViewSet(ViewSet):
    queryset = Article.objects.all()

    def list(self, request):
        serializer = ArticleSerializer(ArticleViewSet.queryset, many=True)
        return Response({article['id']: article for article in serializer.data})

    def retrieve(self, request, pk=None):
        # ...
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.