[Fixed]-Unable to get a non-model field in the validated_data of a Django Rest Framework serializer


You can add non-model fields back by overwriting the to_internal_value fn:

def to_internal_value(self, data):
    internal_value = super(MySerializer, self).to_internal_value(data)
    my_non_model_field_raw_value = data.get("my_non_model_field")
    my_non_model_field_value = ConvertRawValueInSomeCleverWay(my_non_model_field_raw_value)
        "my_non_model_field": my_non_model_field_value
    return internal_value

Then you can process it however you want in create or update.


If you’re doing a PUT request, your view is probably calling self.perform_update(serializer). Change it for

serializer.save(<my_non_model_field>=request.data.get('<my_non_model_field>', <default_value>)

All kwargs are passed down to validated_data to your serializer.
Make sure to properly transform incoming value (to boolean, to int, etc.)

Leave a comment