O S O S - 3 months ago 19
Python Question

django rest change json response design

I'm working with the Django rest tutorial and I see that all the responses are return only the models fields, for example:

[
{
"id": 1,
"title": "",
"code": "foo = \"bar\"\n",
"linenos": false,
"language": "python",
"style": "friendly"
}]


My question is how i can design the response for example:

users:[
{
"id": 1,
"title": "",
"code": "foo = \"bar\"\n",
"linenos": false,
"language": "python",
"style": "friendly"
}]

Answer

From what I can tell, you are using the following code, which I have modified to do what you have requested. However, I would suggest that unless you have very good reason to do so, to not modify how the response is given. It leads to complications in creating multiple objects in the future for ModelViewSets, and all list() methods would return different values.

I really don't like the below, but it does answer the question. In addition, you could change the serializer to be a nested serializer, but that's another question on its own.

from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from snippets.models import Snippet
from snippets.serializers import SnippetSerializer


@api_view(['GET', 'POST'])
def snippet_list(request):
    """
    List all snippets, or create a new snippet.
    """
    if request.method == 'GET':
        snippets = Snippet.objects.all()
        serializer = SnippetSerializer(snippets, many=True)
        return Response({'users': serializer.data})

    elif request.method == 'POST':
        # Assuming we have modified the below - we have to hack around it
        serializer = SnippetSerializer(data=request.data['users'])
        if serializer.is_valid():
            serializer.save()
            return Response({'users': serializer.data}, status=status.HTTP_201_CREATED)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

The above should give you the below response:

{
    "users": [
        {
            "id": 1,
            "title": "",
            "code": "foo=\"bar\"\n",
            "linenos": false,
            "language": "python",
            "style": "friendly"
        },
        {
            "id": 2,
            "title": "",
            "code": "print\"hello, world\"\n",
            "linenos": false,
            "language": "python",
            "style": "friendly"
        }
    ]
}
Comments