django api框架获得总页数

问题描述 投票:7回答:2

是否可以获得API请求可用的页数?例如,这是我的回答:

{
    "count": 44,
    "next": "http://localhost:8000/api/ingested_files/?page=2",
    "previous": null,
    "results": [
        {
            "id": 44,
....

我每页拉20个元素,所以总共应该有2个页面,但是目前它的设置方式我可以获得下一个和之前的页面,但是没有关于页面总量的上下文。当然,我可以做一些数学计算,并使用计数得到多少可能的页面,但我想这样的东西对于框架来说是原生的,不是吗?

这是我的看法:

 class IngestedFileView(generics.ListAPIView):
    queryset = IngestedFile.objects.all()
    serializer_class = IngestedFileSerializer

这是我的序列化器:

class IngestedFileSerializer(serializers.ModelSerializer):
    class Meta:
        model = IngestedFile
        fields = ('id', 'filename', 'ingested_date', 'progress', 'processed', 'processed_date', 'error')
django
2个回答
13
投票

您可以创建自己的分页序列化程序:

from django.conf import settings
from rest_framework import pagination


class YourPagination(pagination.PageNumberPagination):

    def get_paginated_response(self, data):
        return Response({
            'links': {
               'next': self.get_next_link(),
               'previous': self.get_previous_link()
            },
            'count': self.page.paginator.count,
            'total_pages': self.page.paginator.num_pages,
            'results': data
        })

settings.py的配置中,添加YourPagination类作为默认分页类。

REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'my_project.apps.pagination.YourPagination',
    'PAGE_SIZE': 20
}

参考文献:


0
投票

您可以扩展PageNumberPagination类并覆盖get_paginated_response方法以获取总页数。

class PageNumberPaginationWithCount(pagination.PageNumberPagination):
    def get_paginated_response(self, data):
        response = super(PageNumberPaginationWithCount, self).get_paginated_response(data)
        response.data['total_pages'] = self.page.paginator.num_pages
        return response

然后在settings.py中,将PageNumberPaginationWithCount类添加为Default Pagination Class。

REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'my_project.apps.pagination.PageNumberPaginationWithCount',
    'PAGE_SIZE': 30
}
© www.soinside.com 2019 - 2024. All rights reserved.