在django-rest-framework中使用.to_representation()和.to_internal_value?

[英]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?

.to_representation()和.to_internal_value在序列化程序中做了什么?如果我将数据传递给序列化程序,数据是否首先抛出to_representation()?这两个用法是什么用的?

1 个解决方案

#1


15  

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.

如果要创建自定义字段,则需要子类化Field,然后覆盖.to_representation()和.to_internal_value()方法中的一个或两个。这两种方法用于在初始数据类型和原始可序列化数据类型之间进行转换。原始数据类型通常是数字,字符串,布尔值,日期/时间/日期时间或无。它们也可以是任何列表或字典,如仅包含其他原始对象的对象。可能支持其他类型,具体取决于您使用的渲染器。

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

调用.to_representation()方法将初始数据类型转换为基本的可序列化数据类型。

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.

调用to_internal_value()方法将原始数据类型恢复为其内部python表示形式。如果数据无效,此方法应引发serializers.ValidationError。

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.

请注意,版本2.x中存在的WritableField类不再存在。如果字段支持数据输入,则应该子类化Field并覆盖to_internal_value()。

Ref:

参考:

  1. http://www.django-rest-framework.org/api-guide/fields/#custom-fields
  2. http://www.django-rest-framework.org/api-guide/fields/#custom-fields
  3. https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/serializers.py#L417
  4. https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/serializers.py#L417
智能推荐

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.silva-art.net/blog/2015/12/10/535202ae3e4a76d8725bc8bdac86131e.html



 
© 2014-2019 ITdaan.com 粤ICP备14056181号  

赞助商广告