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

qfe3c7zg  于 2022-11-26  发布在  Go
关注(0)|答案(2)|浏览(111)

我正在用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 * 数据类型呈现,并且没有给出关于其内容的提示,它们就像其他字段一样。
现在您可以看到这里的问题,因为我想通知用户,有一个只读字段不应该作为嵌套数据的一部分发送,但我看不到这样做的方法。
理想的情况是在"数据类型"列中有一个模型描述,就像响应类section一样。
有没有适当的方法?

cbjzeqam

cbjzeqam1#

**1.**所有内容请使用drf-yasg作为文档。
**2.**您可以在我一个存储库Kirpi中找到它的实现,并了解如何使用它。
3.如果您在3.;有问题,请告诉我。

vatpfxk5

vatpfxk52#

尝试使用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)

相关问题