DRF序列化器返回可为空的字段

时间:2018-10-08 13:45:27

标签: django django-rest-framework

在drf序列化程序中,如果发布数据中没有值,如何仍将字段名保留为空值?

我正在使用3.3.3版

TextView

当前输出为style="@style/MaterialAnimations"

所需的输出为TYPES = [ ("abc", "abc"), ("def", "def"), ] class MySerializer(serializers.Serializer): choice = serializers.ChoiceField(choices=TYPES, required=False, initial=None) serializer = MySerializer(data={}) serializer.is_valid() print serializer.data

1 个答案:

答案 0 :(得分:1)

选中此项,它应该返回您期望的结果

class MySerializer(serializers.Serializer):
    choice = serializers.ChoiceField(choices=TYPES, required=False, allow_blank=True)
    def to_representation(self, instance):
        ret = super().to_representation(instance)
        if 'choice' in ret:
           return ret
        else:
            ret.update({'choice':''})
            return ret

查看文档以获取to_representation的功能 https://www.django-rest-framework.org/api-guide/serializers/#to_representationself-obj