[Fixed]-What is Serializers to_internal_value method used for in Django


To update the foreign fields for a serializer we use serializer.relatedField which have two functions: to_representation and to_internal_value. to_representation is used to modify the GET body for your API and to_internal_value is used to validate the update request for your serializer, for example, it will help you in checking if the request for updating relatedField is present in the other table or not and things like that.

Let’s say we have 2 models. One is Foo and the other is Bar, and Foo is Foreign Key to Bar, so we need to write the following serializer to validate and update foreign keys that way.

Here is the code snippet:-

class FooField(serializers.RelatedField):

    def to_representation(self, obj):
        return {
            'id': obj.id,
            'name': obj.name,

    def to_internal_value(self, data):
                obj_id = data['id']
                return Obj.objects.get(id=obj_id)
            except KeyError:
                raise serializers.ValidationError(
                    'id is a required field.'
            except ValueError:
                raise serializers.ValidationError(
                    'id must be an integer.'
        except Obj.DoesNotExist:
            raise serializers.ValidationError(
            'Obj does not exist.'

class BarSerializer(ModelSerializer):
    foo = FooField(
    class Meta:
        model = Bar

Hope this will help you.


Leave a comment