user840718
user840718

Reputation: 1611

Django Rest Framework - Wrapping the JSON response with the name of the model

My goal is to customize the JSON response from Django DRF when listing items.

The model:

class Object(models.Model):
    code = models.CharField(max_length=16, primary_key=True, unique=True)
    item = models.CharField(max_digits=128)
    last_updated = models.DateTimeField(auto_now=True, editable=False)

the serializer:

class ObjectSerializer(serializers.ModelSerializer):
    class Meta:
        model = Object
        fields = ['code', 'item']

the view:

class ObjectList(generics.ListAPIView):
    queryset = Object.objects.all()
    serializer_class = ObjectSerializer

    def list(self, request):
        queryset = self.get_queryset()
        serializer = ObjectSerializer(queryset, many=True)
        return Response(serializer.data)

with this setup the JSON response is:

[
    {
        "code": "111",
        "item": "aaa"
    },
    {
        "code": "222",
        "item": "bbb"
    }
]

Is there a way to wrap the response with the name of the model? Expected result would be:

"objects": [
    {
        "code": "111",
        "item": "aaa"
    },
    {
        "code": "222",
        "item": "bbb"
    }
]

Upvotes: 2

Views: 777

Answers (1)

neverwalkaloner
neverwalkaloner

Reputation: 47364

You can customize response on view level, just wrap serializer's data into outer dictionary:

class ObjectList(generics.ListAPIView):
    queryset = Object.objects.all()
    serializer_class = ObjectSerializer

    def list(self, request):
        queryset = self.get_queryset()
        serializer = ObjectSerializer(queryset, many=True)
        return Response({"objects": serializer.data})

Upvotes: 2

Related Questions