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

Django集成Swagger触发AttributeError:rest_framework.serializers无NullBooleanField属性

问题描述

在Django环境中未手动导入相关内容时,由OpenAPISchemaGenerator触发以下错误:

File "/opt/hostedtoolcache/Python/3.8.13/x64/lib/python3.8/site-packages/drf_yasg/inspectors/field.py", line 406, in <module>
    (serializers.NullBooleanField, (openapi.TYPE_BOOLEAN, None)),
AttributeError: module 'rest_framework.serializers' has no attribute 'NullBooleanField'

已查阅相关问题但未获得有效解答,寻求解决方案。

解决方法

  • 升级drf-yasg到兼容版本:
    执行pip install --upgrade drf-yasg,确保安装1.21.0及以上版本,这类版本已经适配了DRF移除NullBooleanField的改动。
  • 临时兼容补丁(不推荐长期使用):
    若暂时无法升级依赖,可在项目初始化文件(如settings.py)中添加以下代码:
    from rest_framework import serializers
    if not hasattr(serializers, 'NullBooleanField'):
        serializers.NullBooleanField = serializers.BooleanField
    
  • 替换项目内的NullBooleanField引用:
    若项目自身代码仍在使用NullBooleanField,直接替换为BooleanField(allow_null=True),这是DRF官方推荐的替代方案,可避免后续更多兼容性问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 16:01:10