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

20👍

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):
        try:
            try:
                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(
        queryset=Foo.objects.all()
    )
    class Meta:
        model = Bar

Hope this will help you.

👤pjoshi

Leave a comment