Skip to content
Advertisement

Can’t add a field to serializer.data django rest

I have a view that displays the project by ID. I want to add one more value into response, but for some reason it is not added.

class ProjectApiView(APIView):

    def get(self, request, project_id=None):
        if project_id:
            project = Project.objects.get(id=project_id)
            serializer = ProjectSerializer(project)
            serializer.data["all_users"] = 'test'
            print(serializer.data)
            return JsonResponse({'project': serializer.data})
class ProjectSerializer(serializers.ModelSerializer):
    prototype = PrototypeSerializer(read_only=True)

    class Meta:
        model = Project
        fields = ['id', 'name', 'prototype', 'colors']

Serializer.data

{'id': 2, 'name': 'test 2', 'prototype': OrderedDict([('id', 1), ('device_name', 'iphone'), ('width', 900), ('height', 1200), ('image', '/media/blank'), ('image_hover', '/media/blank')]), 'colors': {}}

Advertisement

Answer

This is because the .data is a property [GitHub]. What thus happens is that you fetch the value for the .data property, then you manipulate that result, but that is not an object stored at the serializer. If you use serializer.data the next time, then again the method behind the property will run, and of course not take into account what happened to the result the previous run.

You can however simply retrieve the data from the serializer and then alter the outcome of the serializer:

I have a view that displays the project by ID. I want to add one more value into response, but for some reason it is not added.

class ProjectApiView(APIView):

    def get(self, request, project_id=None):
        if project_id:
            project = Project.objects.get(id=project_id)
            serializer = ProjectSerializer(project)
            result = serializer.data
            result['all_users'] = 'test'
            print(result)
            return JsonResponse({'project': result})
Advertisement