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

如何为drf-spectacular请求体字段添加自定义描述?

解决DRF Spectacular请求体字段添加自定义描述的方法

方法1:利用序列化器字段的help_text参数(最简单直接)

DRF Spectacular会自动读取序列化器字段的help_text值,并将其作为OpenAPI文档中的字段描述,这是官方推荐的标准做法,无需额外装饰器。

示例代码:

from rest_framework import serializers

class YourSerializer(serializers.Serializer):
    username = serializers.CharField(
        max_length=50,
        help_text="请输入长度不超过50的用户名,支持中英文、数字及下划线"
    )
    email = serializers.EmailField(
        help_text="必须为有效的邮箱格式,用于接收系统通知"
    )

生成的API文档中,每个字段的描述会直接显示help_text的内容。

方法2:使用@extend_schema_field返回自定义OpenAPI Schema

如果需要更灵活的字段定义(同时修改类型、示例和描述),可以通过@extend_schema_field返回OpenApiSchema对象,而非仅指定类型。

示例代码:

from drf_spectacular.utils import extend_schema_field, OpenApiSchema
from drf_spectacular.types import OpenApiTypes
from rest_framework import serializers

class YourSerializer(serializers.Serializer):
    @extend_schema_field(
        OpenApiSchema(
            type=OpenApiTypes.STR,
            description="请输入长度不超过50的用户名,支持中英文、数字及下划线",
            example="test_user_01"
        )
    )
    username = serializers.CharField(max_length=50)

这种方式可完全自定义字段的OpenAPI元数据,包括描述、类型、示例等。

方法3:在视图中通过@extend_schema覆盖请求体Schema

如果需在视图级别调整请求体字段描述、不修改序列化器,可使用@extend_schema的request参数传入自定义请求体定义。

示例代码:

from drf_spectacular.utils import extend_schema
from rest_framework.views import APIView
from .serializers import YourSerializer

class YourAPIView(APIView):
    @extend_schema(
        request={
            "application/json": {
                "type": "object",
                "properties": {
                    "username": {
                        "type": "string",
                        "description": "请输入长度不超过50的用户名,支持中英文、数字及下划线",
                        "maxLength": 50,
                        "example": "test_user_01"
                    },
                    "email": {
                        "type": "string",
                        "format": "email",
                        "description": "必须为有效的邮箱格式,用于接收系统通知",
                        "example": "test@example.com"
                    }
                },
                "required": ["username", "email"]
            }
        },
        responses=200
    )
    def post(self, request):
        # 视图逻辑
        pass

该方式适合临时调整单个视图的请求体字段描述,不影响全局序列化器定义。

常见问题排查

  • 若之前使用@extend_schema_field未成功,大概率是仅传入了类型(如OpenApiTypes.STR)而非OpenApiSchema对象,后者才支持description参数。
  • 确保DRF Spectacular为最新版本,旧版本可能存在help_text解析不完整的问题,可执行升级:pip install --upgrade drf-spectacular

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 18:15:18