You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django Rest Framework序列化器报错:JSON请求触发非空校验异常

问题分析与解决

问题场景

使用如下Django REST Framework序列化器和视图类:

class AdvanceSearchSerializer(serializers.Serializer):
    all_of_these_words = serializers.CharField(allow_null=True, required=False)
    this_exact_phase = serializers.CharField(allow_null=True, required=False)
    any_of_these_words = serializers.CharField(allow_null=True, required=False)


class myclass(viewsets.Viewsets):
    serializer = AdvanceSearchSerializer(data = request.data)

通过Postman以form-data格式发送POST请求功能正常,但切换为raw JSON格式请求后,触发字段不能为空的错误:

{
    "response": false,
    "return_code": "field_error",
    "result": [],
    "message": {
        "all_of_these_words": [
            "This field may not be blank."
        ],
        "this_exact_phase": [
            "This field may not be blank."
        ],
        "any_of_these_words": [
            "This field may not be blank."
       ]
    }
}

问题原因

allow_null=True仅允许字段值为null,但用JSON格式请求时,你可能传递了空字符串("")而非null,而CharField默认不允许空字符串,因此触发校验错误。

而form-data格式下,未填写的字段不会被提交到后端,序列化器将其视为不存在,符合required=False的设置,所以不会报错。

解决方法

在序列化器的CharField中添加allow_blank=True参数,同时保留allow_null=True和required=False,这样既允许字段不传递,也允许传递null或空字符串:

class AdvanceSearchSerializer(serializers.Serializer):
    all_of_these_words = serializers.CharField(allow_null=True, required=False, allow_blank=True)
    this_exact_phase = serializers.CharField(allow_null=True, required=False, allow_blank=True)
    any_of_these_words = serializers.CharField(allow_null=True, required=False, allow_blank=True)

内容的提问来源于stack exchange,提问作者smjadeja

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 01:31:17