[Fixed]-Override serializer.data in Django REST Framework

14👍

I checked out serializer.data with dir() and it’s just a python dictionary so I can’t figure out why I can’t modify the value.

While the value returned from Serializer.data is indeed a dictionary, Serializer.data is not a simple instance variable.

If you look at rest_framework/serializers.py:

class Serializer(BaseSerializer, metaclass=SerializerMetaclass):
    # [...]
    @property
    def data(self):
        ret = super().data
        return ReturnDict(ret, serializer=self)

ReturnDict inherits from OrderedDict, but you still get a new dictionary every time you access Serializer.data.

The real data is in _data, however as noted by the underscore you might not want to modify that either as it is not intended to be public. The values are filled by Serializer.to_representation() which you could override on the viewset.

As for the second part: ModelViewSet defines get_serializer() that is called with the request POST data to create the serializer you want to modify. I’d suggest try to change the input data before the serializer is created, instead.

👤dhke

Leave a comment