Django SerializerMethodField无法保存小数

时间:2018-04-20 22:53:06

标签: django django-rest-framework

因此,根据文档,SerializerMethodField是一个只读字段。

在我的情况下,它干扰了我的写作:

# old value is 2.5
data={'score': 1.7}
serializer = ScoreTraitSerializer(
        score_trait, data=data, partial=True)
    if serializer.is_valid():
        new_score_trait = serializer.save()

现在,如果我检查new_score_trait,我的分数仍为2.5

序列化器看起来像这样:

score = serializers.SerializerMethodField()

def get_score(self, obj):
    if isinstance(obj.score, decimal.Decimal):
        return float(obj.score)
    else:
        return obj.score

如果我注释掉SerializerMethodField,我可以保存新的十进制值(但无法将其序列化)。

所以......我正确使用我的序列化器吗?为什么我对序列化程序的写入命中SerializerMethodField

提前致谢

1 个答案:

答案 0 :(得分:1)

SerializerMethodField是一个只读字段。仅用于to_representation,用于list/retrieve而不是create/update

序列化程序字段分数必须与模型字段分数冲突,请尝试将其更改为:

float_score = serializers.SerializerMethodField(required=False)

def get_float_score (self, obj):
    if isinstance(obj.score, decimal.Decimal):
        return float(obj.score)
    else:
        return obj.score

请参阅源代码,了解原因:

class SerializerMethodField(Field):
    """
    A read-only field that get its representation from calling a method on the
    parent serializer class. The method called will be of the form
    "get_{field_name}", and should take a single argument, which is the
    object being serialized.

    For example:

    class ExampleSerializer(self):
        extra_info = SerializerMethodField()

        def get_extra_info(self, obj):
            return ...  # Calculate some data to return.
    """
    def __init__(self, method_name=None, **kwargs):
        self.method_name = method_name
        kwargs['source'] = '*'
        kwargs['read_only'] = True
        super(SerializerMethodField, self).__init__(**kwargs)