首页 > 解决方案 > DRF 序列化程序返回可为空的字段

问题描述

在 drf 序列化程序中,如果 post 数据中没有值,我如何仍然保持字段名称为空值?

我正在使用版本 3.3.3

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

电流输出为{}

所需的输出是{'choice': None}

标签: djangodjango-rest-framework

解决方案


检查这个它应该返回你所期望的

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


推荐阅读