【发布时间】:2022-12-14 02:28:17
【问题描述】:
我有一个用例,其中请求所需的字段根据请求的字段值之一而不同。
例如,如果请求中的可移动类型的值为'P',则部分字段为必填,否则,如果移动类型的值为'D',则其他部分字段为必填。
如何使用 drf-yasg 为此类用例创建自定义请求?
【问题讨论】:
标签: django django-rest-framework swagger-ui drf-yasg
我有一个用例,其中请求所需的字段根据请求的字段值之一而不同。
例如,如果请求中的可移动类型的值为'P',则部分字段为必填,否则,如果移动类型的值为'D',则其他部分字段为必填。
如何使用 drf-yasg 为此类用例创建自定义请求?
【问题讨论】:
标签: django django-rest-framework swagger-ui drf-yasg
根据我在drf_yasg docs 中发现的内容,您需要实现一个名为Inspector班级要自定义与特定字段、序列化器、过滤器或分页器类相关的行为,您可以实现 FieldInspector、SerializerInspector、FilterInspector、PaginatorInspector 类,并将它们与 @swagger_auto_schema 或 related settings 之一一起使用.
这是一个 FieldInspector 的示例,它从所有生成的 Schema 对象中删除 title 属性并取自 Inspector classes [drf_yasg-docs] :
from drf_yasg.inspectors import FieldInspector class NoSchemaTitleInspector(FieldInspector): def process_result(self, result, method_name, obj, **kwargs): # remove the `title` attribute of all Schema objects if isinstance(result, openapi.Schema.OR_REF): # traverse any references and alter the Schema object in place schema = openapi.resolve_ref(result, self.components) schema.pop('title', None) # no ``return schema`` here, because it would mean we always generate # an inline `object` instead of a definition reference # return back the same object that we got - i.e. a reference if we got >a reference return result class NoTitleAutoSchema(SwaggerAutoSchema): field_inspectors = [NoSchemaTitleInspector] + >swagger_settings.DEFAULT_FIELD_INSPECTORS class ArticleViewSet(viewsets.ModelViewSet): swagger_schema = NoTitleAutoSchema ...
【讨论】: