3

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"
      }]
O S
  • 73
  • 6
  • I do not understand what the question is , could you be more descriptive? Thanks in advance! – mkarts Aug 15 '16 at 13:56
  • Thank for the response, is my example isn't good? – O S Aug 15 '16 at 14:00
  • The only difference between the 2 code samples you posted are almost the same. What is your problem, what is your desired output and what have you done so far? :D – mkarts Aug 15 '16 at 14:02
  • He wants to add a root element. http://stackoverflow.com/questions/14824807/adding-root-element-to-json-response-django-rest-framework – masnun Aug 15 '16 at 14:03
  • As I wrote, I follwing the django rest tutorial (http://www.django-rest-framework.org/tutorial/2-requests-and-responses/?q=viewsets.ModelViewSet) and i'm asking if I can take the examples and add them names for the json objects, like in my second example, that i added the word "users" – O S Aug 15 '16 at 14:05

1 Answers1

1

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"
        }
    ]
}
Michael B
  • 5,148
  • 1
  • 28
  • 32
  • Thank you for your help! How can i combine in the response two models that doesn't have any relationship between them? For example 'users' and 'address' – O S Aug 16 '16 at 07:38
  • It is the same methodology. Use a different QuerySet with a different serializer, then use a separate key value and pass in the serializer data. – Michael B Aug 16 '16 at 13:23