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?
You will probably have to implement a wrapper for your
CourseSerializer
. Try the code below.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.