Skip to content Skip to sidebar Skip to footer

Update/append Serializer.data In Django Rest Framework

How can I update/append serializer.data in Django Rest Framework? data = serializer.data.update({'item': 'test'}) not working return Response(serializer.data, status=status.HTTP_20

Solution 1:

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

Solution 2:

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.

classUserSerializer(serializers.ModelSerializer):
    days_since_joined = serializers.SerializerMethodField()

    classMeta:
        model = User

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

Solution 3:

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

Solution 4:

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

sample code

classSampleAPIView(generics.CreateAPIView)
    serializer_class = SampleSerializer

    defperform_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

Solution 5:

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

Post a Comment for "Update/append Serializer.data In Django Rest Framework"