admin管理员组文章数量:1122846
I have a simple DRF serializer:
class CustomerFeatureSerializer(serializers.Serializer):
"""
Serializer for a customer feature.
"""
feature_id = serializers.CharField()
feature_value = serializers.SerializerMethodField()
feature_type = serializers.CharField()
name = serializers.CharField()
def get_feature_value(self, obj):
"""
Return the feature_value of the feature.
"""
return obj.get("feature_value", None)
the feature_value
field is a method field since it can be either a boolean, an integer, or a string value (so for now I just kept it as a method field to fetch the value).
I am using this to serialize some objects that I am hand-generating (they do not correspond 1:1 with a model) but for some reason after validation the name
and feature_value
fields are just completely disappearing.
for feature in toggleable_features:
display = {
"feature_id": feature.internal_name,
"name": feature.name,
"feature_value": profile.feature_value(feature)
if profile.has_feature(feature.internal_name, use_cache=False)
else False,
"feature_type": feature.type,
}
features.append(display)
print(display)
print(features)
serializer = CustomerFeatureSerializer(data=features, many=True)
print(serializer.initial_data)
serializer.is_valid(raise_exception=True)
print(serializer.validated_data)
return Response(serializer.validated_data)
and the print statements output:
{'feature_id': 'feat-id', 'name': 'feat name', 'feature_value': True, 'feature_type': 'boolean'}
[{'feature_id': 'feat-id', 'name': 'feat name', 'feature_value': True, 'feature_type': 'boolean'}]
[{'feature_id': 'feat-id', 'name': 'feat name', 'feature_value': True, 'feature_type': 'boolean'}]
[OrderedDict([('feature_id', 'feat-id'), ('feature_type', 'boolean'), ('name', 'feat name')])]
the value is just gone. Any idea why this could be happening? Is the object I am serializing not valid somehow?
本文标签: pythonDRF serializer missing fields after validationStack Overflow
版权声明:本文标题:python - DRF serializer missing fields after validation - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736307462a1933318.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论