[Django]-Update/append serializer.data in Django Rest Framework

66👍

Unfortunately, serializer.data is a property of the class and therefore immutable. Instead of adding items to serializer.data you can copy serializer.data to another dict. You can try this:

newdict={'item':"test"}
newdict.update(serializer.data)
return Response(newdict, status=status.HTTP_201_CREATED)

Read more about property

9👍

Alternatively you might use SerializerMethodField to add additional data by adding a custom method to the serializer.

http://www.django-rest-framework.org/api-guide/fields/#serializermethodfield

You can use such a method to return any data, wether in context of the model or not.

class UserSerializer(serializers.ModelSerializer):
    days_since_joined = serializers.SerializerMethodField()

    class Meta:
        model = User

    def get_days_since_joined(self, obj):
        return (now() - obj.date_joined).days

8👍

You don’t.

If you need to pass extra data to the serializer’s create/update please do so while calling serializer.save() as explained in the documentation

5👍

We can update the data passed in response with serializer._data

sample code

class SampleAPIView(generics.CreateAPIView)
    serializer_class = SampleSerializer

    def perform_update(self, serializer):
        application = serializer.save(status='pending')
        my_response_data = {'id': 110, 'name': 'Batta'}
        serializer._data = out_data

serializer._data will make the magic.
Reference: https://github.com/encode/django-rest-framework/blob/master/rest_framework/serializers.py#L260

4👍

The serializer.data object is a instance of ReturnList that is immutable. What you can do to workaround this limitation is transform the serializer.data object into a simple Python list(), then append the value you want so you can use your transformed list in Response() method like this:

def get(self, request):
    serializer = YourAmazingSerializer(many=True)
    new_serializer_data = list(serializer.data)
    new_serializer_data.append({'dict_key': 'dict_value'})
    return Response(new_serializer_data)

Then, your response will have your new obj

Leave a comment