Django tweak the rest framework serializer to gett

2019-09-04 10:03发布

I have a django app using rest framework in which i am serializing a model in my serializers.py as follows:

class CourseSerializer(serializers.ModelSerializer):

    class Meta:
    model = Course
    depth = 1

and the output i am getting on my api is as follows:

[
    {
        "course_id": 992, 
    }, 
    {
        "course_id": 994, 
    }
]

But now i would like to tweak the json structure a bit and i want to get an output as follows:

[
    {
        "course": {
            "course_id": 992, 
        }
    }, 
    {
        "course": {
            "course_id": 994, 
        }
    }
]

Here is my api.py:

class CourseSubjectList(APIView):
    def get(self, request, pk, format=None):
        subs = Course.objects.all()
        serialized_subs = CourseSerializer(subs, many=True)
        return Response(serialized_subs.data)

How do i achieve this?

1条回答
我命由我不由天
2楼-- · 2019-09-04 10:32

You will probably have to implement a wrapper for your CourseSerializer. Try the code below.

class CourseSerializer(serializers.ModelSerializer):

    class Meta:
    model = Course
    depth = 1


class CourseWrapperSerializer(serializers.Serializer):

    course = CourseSerializer(read_only=True, source='*')

The crucial thing here is source='* indicating that the entire object should be passed through to the field. Then in your view use the wrapper instead of the original serializer.

class CourseSubjectList(APIView):
    def get(self, request, pk, format=None):
        subs = Course.objects.all()
        serialized_subs = CourseWrapperSerializer(subs, many=True)
        return Response(serialized_subs.data)
查看更多
登录 后发表回答