django-rest-swagger 带有只读字段的嵌套序列化程序未正确呈现

问题描述 投票:0回答:3

我正在使用 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 数据类型呈现,并且没有给出有关其内容的提示,它们就像其他字段一样。

现在您可以看到那里的问题,因为我想通知用户有一个只读字段不应作为嵌套数据的一部分发送,但我看不到这样做的方法。

理想的情况是在数据类型列中有一个模型描述,就像响应类部分

有什么正确的方法吗?

python django django-rest-framework documentation-generation
3个回答
0
投票

1. 一切请使用 drf-yasg 文档。

2. 您可以在我的存储库之一 Kirpi 中找到它的实现并学习如何使用它。

3. 如果你在 3. ;有问题,让我知道。


0
投票

尝试使用

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)

0
投票

使用 https://drf-spectacular.readthedocs.io/en/latest/ 现在是这个用例的正确选择。这是维护良好并支持 OpenAPI 3.0+。现在也由 django-rest-framework 本身建议。

© www.soinside.com 2019 - 2024. All rights reserved.