Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usage of .to_representation() and .to_internal_value in django-rest-framework?

What do .to_representation() and .to_internal_value do in serializers?
If I pass data to a serializer, is the data thrown to_representation() first?
What's the usage of these two?

like image 773
nataila Avatar asked Dec 10 '15 07:12

nataila


People also ask

What is To_representation Django REST framework?

to_representation(self, value) method. This method takes the target of the field as the value argument, and should return the representation that should be used to serialize the target. The value argument will typically be a model instance.

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.

Why do we need Serializers in Django REST framework?

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.


1 Answers

If you want to create a custom field, you'll need to subclass Field and then override either one or both of the .to_representation() and .to_internal_value() methods. These two methods are used to convert between the initial datatype, and a primitive, serializable datatype. Primitive datatypes will typically be any of a number, string, boolean, date/time/datetime or None. They may also be any list or dictionary like object that only contains other primitive objects. Other types might be supported, depending on the renderer that you are using.

The .to_representation() method is called to convert the initial datatype into a primitive, serializable datatype.

The to_internal_value() method is called to restore a primitive datatype into its internal python representation. This method should raise a serializers.ValidationError if the data is invalid.

Note that the WritableField class that was present in version 2.x no longer exists. You should subclass Field and override to_internal_value() if the field supports data input.

Ref:

  1. http://www.django-rest-framework.org/api-guide/fields/#custom-fields
  2. https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/serializers.py#L417
like image 157
Geo Jacob Avatar answered Sep 28 '22 06:09

Geo Jacob