我正在使用 django-rest-framework 构建一个 API,并且我开始使用 django-rest-swagger 来制作文档。 我有一个带有一些只读字段的嵌套序列化程序,如下所示:
# this is the nested serializer
class Nested(serializers.Serializer):
normal_field = serializers.CharField(help_text="normal")
readonly_field = serializers.CharField(read_only=True,
help_text="readonly")
# this is the parent one
class Parent(serializers.Serializer):
nested_field = Nested()
在生成的文档中,页面的 Parameters 部分中的嵌套序列化程序使用 field 数据类型呈现,并且没有给出有关其内容的提示,它们就像其他字段一样。
现在您可以看到那里的问题,因为我想通知用户有一个只读字段不应作为嵌套数据的一部分发送,但我看不到这样做的方法。
理想的情况是在数据类型列中有一个模型描述,就像响应类部分。
有什么正确的方法吗?
尝试使用
drf_yasg
代替,Swagger会生成API的文档,但不是绝对正确!
如果你想更正 Swagger 文档,你可以这样做。您将需要使用 swagger_auto_schema
装饰器。下面是示例代码:
from drf_yasg import openapi
from drf_yasg.utils import swagger_auto_schema
class ProductSuspendView(CreateAPIView):
@swagger_auto_schema(
tags=['dashboard'],
request_body=openapi.Schema(
type=openapi.TYPE_OBJECT,
properties={
'id': openapi.Schema(
type=openapi.TYPE_INTEGER,
description='Id',
),
'suspend_kinds': openapi.Schema(
type=openapi.TYPE_ARRAY,
items=openapi.Items(type=openapi.TYPE_INTEGER),
description='Array suspend (Inappropriate image: 1, Insufficient information: 2, Bad language: 3) (suspend_kinds=[1,2])'
),
}
),
responses={
status.HTTP_200_OK: SuccessResponseSerializer,
status.HTTP_400_BAD_REQUEST: ErrorResponseSerializer
}
)
def post(self, request, *args, **kwargs):
"""
Suspend a product.
"""
...
if success:
return Response({'success': True}, status.HTTP_200_OK)
return Response({'success': False}, status.HTTP_400_BAD_REQUEST)
使用 https://drf-spectacular.readthedocs.io/en/latest/ 现在是这个用例的正确选择。这是维护良好并支持 OpenAPI 3.0+。现在也由 django-rest-framework 本身建议。