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