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

What do .to_representation() and .to_internal_value in serializers ?
If I pass the data to the serializer, are the data thrown to_representation() ?
What is the use of these two?

+15
source share
1 answer

If you want to create a custom field, you need to subclass and then override one or both of the .to_representation() and .to_internal_value() methods. These two methods are used to convert between the original data type and the primitive serializable data type. Primitive data types will usually be any of a number, a string, a boolean, a date / time / date / time or not. They can also be any list or dictionary, like an object that contains only other primitive objects. Other types may be supported, depending on which one you use using.

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

The to_internal_value() method is called to restore the primitive. The data type in the internal representation of Python. This method should raise serializers.ValidationError if the data is invalid.

Note that the WritableField class, which was present in version 2.x, does not exist longer. You must subclass Field and override to_internal_value() if the field supports data entry.

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
+19
source

Source: https://habr.com/ru/post/1237828/


All Articles