本文介绍了drf-yasg定制json主体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在基于Classd的django视图中自定义drf-yasg模式?

How to customize drf-yasg schema in ClassBased django views?

我尝试了这部分代码,但是所产生的挥霍不尊重更改.

I tried this part of code, but the generated swagger doesn't respect the change.

class CustomView(CreateAPIView):
    permission_classes = (IsAuthenticated,)
    serializer_class = CustomSerializer

    @swagger_auto_schema(request_body=openapi.Schema(
        type=openapi.TYPE_OBJECT,
        properties={
            'phone': openapi.Schema(type=openapi.TYPE_STRING, description='string'),
            'body': openapi.Schema(type=openapi.TYPE_STRING, description='string'),
        }))
    def create(self, request: Request, *args, **kwargs):
        phone = request.data.get('phone')
        body = request.data.get('body')
        ...

推荐答案

我找到了,这里是正确的代码:

I found it, here is the right code:

class CustomView(CreateAPIView):
    permission_classes = (IsAuthenticated,)
    serializer_class = CustomSerializer
    http_method_names = ['post']

    @swagger_auto_schema(request_body=openapi.Schema(
        type=openapi.TYPE_OBJECT,
        properties={
            'phone': openapi.Schema(type=openapi.TYPE_STRING, description='The desc'),
            'body': openapi.Schema(type=openapi.TYPE_STRING, description='The desc'),
        }))
    def post(self, request: Request, *args, **kwargs):
        phone = request.data.get('phone')
        body = request.data.get('body')
        ...

对于IN_QUERY类型,如下所示:

And for IN_QUERY type, like this:

class CustomListView(ListAPIView):
    permission_classes = (IsAuthenticated,)
    serializer_class = CustomSerializer
    http_method_names = ['get']

    @swagger_auto_schema(manual_parameters=[
        openapi.Parameter('obj_id', openapi.IN_QUERY,
                          type=openapi.TYPE_STRING),
    ])
    def get(self, request, *args, **kwargs):
        obj_id = self.request.DATA.get('obj_id')

这篇关于drf-yasg定制json主体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 10:32