django - 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}
解决方案
检查这个它应该返回你所期望的
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
推荐阅读
- java - Java中有没有办法按照固定的平均值和标准偏差生成随机数?
- javascript - 提交表单,其中输入是php中的数组
- postgresql - 无法使用命令行连接 Postgres
- laravel - AWS 上的 Laravel:日志文件权限问题
- visual-recognition - 为提供的服务指南找到 0 个密钥
- amazon-web-services - 如何通过 AWS API Gateway 将多个 Cognito 用户池用于单个终端节点?
- regex - 将正则表达式从 bash 转换为 zsh
- sql - Big Query 数据总数错误,LEFT JOIN 后怀疑重复行
- ios - ios 13上的alamofire调用失败
- function - 芭蕾舞演员中的未定义函数