1

目前我在 drf 上使用 LimitOffsetPagination,并使用 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.

我想知道有没有办法在这些操作视图上自动生成/添加分页响应模式和参数。

如果我使用SubModel1Serializer(many=True)on swagger_auto_schema(responses={...}),响应模式将仅显示为 SubModel1s(或 2s)的数组,没有 prev、next、items 等字段。

谢谢你。

4

2 回答 2

2

我们需要创建一个分页器检查器类并在paginator_inspectors参数下提供它,swagger_auto_schema或者可以将该分页器类添加到 in 下的全局设置DEFAULT_PAGINATOR_INSPECTORSSWAGGER_SETTINGS。我自己创建了一个分页器类,将在此处提供作为示例。我跟着 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)
        ]```
于 2020-10-14T23:36:07.040 回答
0

解决方案是在一个视图集上有多个查询集和序列化程序。

    querysets = {
        'submodel1': SubModel1.objects.all(),
        'submodel2': SubModel2.objects.all()
    }
    serializer_classes = {
        'submodel1': SubModel1Serializer,
        'submodel2': SubModel2Serializer
    }

    def get_queryset(self):
        if self.action in self.querysets:
            return self.querysets[self.action]
        return super().get_queryset()

    def get_serializer_class(self):
        if self.action in self.querysets:
            return self.serializer_classes[self.action]
        return super().get_serializer_class()

它就像魔术一样起作用。(❁´◡`❁)

于 2020-04-25T00:24:51.743 回答