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?
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.
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.
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.
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 overrideto_internal_value()
if the field supports data input.
Ref:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With