Django Rest Framework 嵌套列表视图

Django RestFramework Nested List view

我只想嵌套对象的 ListView,如下所示:

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

然而我只能得到这样的结果:

[
    {
        "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)

我尝试嵌套序列化程序,但我嵌套了每个对象。我需要的是对象列表的嵌套结果。 我该怎么做?谢谢你的帮助! :)

在返回响应时,您可以像这样创建一个字典。 return Response({'Organizations': serializer.data})

不要 return 直接序列化器而是 return dictionary

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