如何在DRF-YASG中消除dwagger-u中的id路径参数,用于DRF和DJANGO



我正在使用DRF-YASG在Swagger中记录API,并希望自定义/消除参数中显示的一些字段

我正在使用Django 2.1.7,DRF 3.9.2和DRF-YASG 1.14.0运行该项目。

所以,我想消除在 swagger-ui 中显示的 ID(如"字符串"和"路径"(,因为我通过 Schema 在正文请求中拥有它,但 swagger-ui 在参数中显示 id(自动生成的字段(。

在下面的屏幕中,您可以看到问题:

https://user-images.githubusercontent.com/5421182/54859641-70359d00-4cee-11e9-9b12-79ab57d12495.png

在这里,我的代码...

request_category_put = openapi.Schema(type=openapi.TYPE_OBJECT, required=['id','name'],
    properties={
        'id': openapi.Schema(type=openapi.TYPE_INTEGER, 
                title='Id', readOnly=True,
                description='Id of the category'), ### <-- I have the ID here.
        'name': openapi.Schema(type=openapi.TYPE_STRING, 
                title='Category', maxLength=200, minLength=1,
                description='Name of the category')
    },
    example={
        'id' : 1,
        'name' : 'Business',
    }
)
class CategoryDetail(APIView):
    permission_classes = (IsAuthenticatedOrReadOnly,)
    @swagger_auto_schema(
        manual_parameters=[authorization],
        request_body=request_category_put,
        responses = {
            '200' : response_category,
            '400': 'Bad Request',
            '404': 'Not found'
        },        
        security=[security_endpoint],
        operation_id='Update category',
        operation_description='Update a specific category.',
    )
    def put(self, request, pk, format=None):
        category = get_object_or_404(Category, pk=pk)
        serializer = CategorySerializer(category, data=request.data)
        if serializer.is_valid():
            serializer.save(modified_by=self.request.user)
            return Response(serializer.data, status=status.HTTP_200_OK)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

当我在@swagger_auto_schema中添加manual_parameters字段中时,只更改此属性...但田野仍然存在。

查看代码以了解manual_parameters是如何实现的,这看起来是不可能的。看: drf_yasg.inspectors.view.get_operation()

    def get_operation(self, operation_keys=None):
        operation_keys = operation_keys or self.operation_keys
        consumes = self.get_consumes()
        produces = self.get_produces()
        body = self.get_request_body_parameters(consumes)
        query = self.get_query_parameters()
        parameters = body + query
        parameters = filter_none(parameters)
        parameters = self.add_manual_parameters(parameters)

在该函数中,有一个对 add_manual_parameters() 的调用,它仅将您指定的覆盖添加到现有的参数列表中。因此,您必须添加一个选项来替换现有的参数或添加新的manual_overrides_remove以删除特定参数。我建议在 drf_yasg github 页面中提出问题或提交 PR 以添加此功能。

尝试添加要从 serrializer 元字段read_only_fields中的招摇请求描述中排除的参数名称

喜欢

class SomeSerializer(ModelSerializer):
    ...
    class Meta:
        ...
        read_only_fields = ["id", ...]

最新更新