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

31👍

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

Leave a comment