如何获得基于序列化程序(drf-yasg)的分页响应模式



目前我正在drf上使用LimitOffsetPaging,并使用drf-yasg记录API。

我写了一个这样的视图:

class MyViewSet(GenericViewSet):
@action(detail=False, methods=['get'])
def submodel1(self, request):
queryset = SubModel1.objects.filter(user=request.user)
queryset = self.paginate_queryset(queryset.all())
serializer = SubModel1Serializer(queryset, many=True)
return self.get_paginated_response(serializer.data)
@action(detail=False, methods=['get'])
def submodel2(self, request):
queryset = SubModel2.objects.filter(user=request.user)
queryset = self.paginate_queryset(queryset.all())
serializer = SubModel2Serializer(queryset, many=True)
return self.get_paginated_response(serializer.data)

现在我想用swagger_auto_schema来记录它。

我想知道是否有一种方法可以在这些操作视图上自动生成/添加分页响应模式和参数。

如果在swagger_auto_schema(responses={...})上使用SubModel1Serializer(many=True),则响应模式将仅显示为SubModel1s(或2s(的数组,而不包含prev、next、items等字段。

谢谢。

我们需要创建一个分页器检查器类,并在swagger_auto_schemapaginator_inspectors参数下提供它,或者可以将该分页器类添加到SWAGGER_SETTINGSDEFAULT_PAGINATOR_INSPECTORS下的全局设置中。我自己创建了一个分页器类,将在这里提供一个示例。我遵循了LimitOffsetPagination。


from drf_yasg.inspectors import PaginatorInspector
from drf_yasg import openapi

class LimitOffsetPaginatorInspectorClass(PaginatorInspector):
def get_paginated_response(self, paginator, response_schema):
"""
:param BasePagination paginator: the paginator
:param openapi.Schema response_schema: the response schema that must be paged.
:rtype: openapi.Schema
"""
return openapi.Schema(
type=openapi.TYPE_OBJECT,
properties=OrderedDict((
('count', openapi.Schema(type=openapi.TYPE_INTEGER)),
('next', openapi.Schema(
type=openapi.TYPE_OBJECT,
properties=OrderedDict((
('offset', openapi.Schema(type=openapi.TYPE_INTEGER)),
('limit', openapi.Schema(type=openapi.TYPE_INTEGER))
))
)),
('results', response_schema),
)),
required=['results']
)
def get_paginator_parameters(self, paginator):
"""
Get the pagination parameters for a single paginator **instance**.
Should return :data:`.NotHandled` if this inspector does not know how to handle the given `paginator`.
:param BasePagination paginator: the paginator
:rtype: list[openapi.Parameter]
"""
return [
openapi.Parameter('offset', openapi.IN_QUERY, "Offset for Pagination", False, None, openapi.TYPE_INTEGER),
openapi.Parameter('limit', openapi.IN_QUERY, "Page Size", False, None, openapi.TYPE_INTEGER)
]```

最新更新