Home > Software design >  Django RestFramework Nested List view
Django RestFramework Nested List view

Time:03-11

I want to nest only the ListView of my objects like this:

{ 
"Organisations":
 [{ 
"OrganisationName": "Organisation1", 
"OrganisationID": "ABC12345" 
}, 
{ 
"OrganisationName": "Organisation2", 
"OrganisationID": "XYZ12345" 
} 
]}

However I can only get results like this:

[
    {
        "OrganisationID": "Organisation1",
        "OrganisationName": "ABC12345"
    },
    {
        "OrganisationID": "Organisation2",
        "OrganisationName": "XYZ12345"
    }
]

models.py:


from django.db import models


class Organisation(models.Model):
    """Model class for the Atomo Organisations"""

    OrganisationName = models.CharField(max_length=60, blank=True, null=True, default="")
    OrganisationID = models.CharField(max_length=60, unique=True, blank=True, null=True, default="")
    
    class Meta:
        ordering = ['OrganisationName']

    def __str__(self):
        """String for representing the MyModelName object (in Admin site etc.)."""
        return self.OrganisationName

serializers.py:

from rest_framework import serializers
from models import Organisation


class OrgSerializer(serializers.ModelSerializer):
    class Meta:
        model = Organisation
        fields = ["OrganisationID", "OrganisationName"]

views.py:

from models import Organisation
from serializers import OrgSerializer
from django.http import Http404
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status

class OrgList(APIView):
    
    def get(self, request, format=None):
        orgs = Organisation.objects.all()
        serializer = OrgSerializer(orgs, many=True)
        return Response(serializer.data)
    
    def post(self, request, format=None):
        serializer = OrgSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

I have tried to nest the serializer but I nests every object. What I need is a nested result of the object lists. How can I do it? Thanks for any help! :)

CodePudding user response:

While returning the response you can create a dictionary like this. return Response({'Organizations': serializer.data})

CodePudding user response:

Don't return serializer directly but return a dictionary

def get(self, request, format=None):
        orgs = Organisation.objects.all()
        serializer = OrgSerializer(orgs, many=True)
        response = {
            "Organisations": serializer.data
        }
        return Response(response)
  • Related