gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 19:07:42 33 4
gpt4 key购买 nike

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

最佳答案

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.

引用:

  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

关于django - 在 django-rest-framework 中使用 .to_representation() 和 .to_internal_value?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34196331/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com