Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is Serializers to_internal_value method used for in Django

Tags:

rest

django

I have some models with foreignKey and serializers with a relatedField. But I have an error saying that to_internal_value needs to be implemented first. However, I don't know the use of this method and could not find any useful reference on the web. Any help explaining this is more than appreciated.

like image 439
Spider Avatar asked Feb 07 '16 18:02

Spider


People also ask

What is the use of Serializers in Django?

Serializers in Django REST Framework are responsible for converting objects into data types understandable by javascript and front-end frameworks. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.

Is it necessary to use Serializers in Django?

If you work with Django rest API. So serializer is a good option to convert data into JSON format. If you don't want to use a serializer you can use Django form rather than serializer.

What are Serializers explain Modelserializers?

The ModelSerializer class provides a shortcut that lets you automatically create a Serializer class with fields that correspond to the Model fields. The ModelSerializer class is the same as a regular Serializer class, except that: It will automatically generate a set of fields for you, based on the model.

What is the difference between ModelSerializer and HyperlinkedModelSerializer?

The HyperlinkedModelSerializer class is similar to the ModelSerializer class except that it uses hyperlinks to represent relationships, rather than primary keys. By default the serializer will include a url field instead of a primary key field.


1 Answers

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.

like image 158
pjoshi Avatar answered Nov 15 '22 07:11

pjoshi