django api框架获得总页数

Stu*_*Cat 8 django

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

{
    "count": 44,
    "next": "http://localhost:8000/api/ingested_files/?page=2",
    "previous": null,
    "results": [
        {
            "id": 44,
....
Run Code Online (Sandbox Code Playgroud)

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

这是我的看法:

 class IngestedFileView(generics.ListAPIView):
    queryset = IngestedFile.objects.all()
    serializer_class = IngestedFileSerializer
Run Code Online (Sandbox Code Playgroud)

这是我的序列化器:

class IngestedFileSerializer(serializers.ModelSerializer):
    class Meta:
        model = IngestedFile
        fields = ('id', 'filename', 'ingested_date', 'progress', 'processed', 'processed_date', 'error')
Run Code Online (Sandbox Code Playgroud)

Eva*_*thi 16

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

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
        })
Run Code Online (Sandbox Code Playgroud)

在您的配置中settings.py,将YourPagination类添加为默认分页类.

REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'my_project.apps.pagination.YourPagination',
    'PAGE_SIZE': 20
}
Run Code Online (Sandbox Code Playgroud)

参考文献:

  • DRF正在使用django paginator?请参阅https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/pagination.py#L177.所以你应该可以通过`self.page.paginator.num_pages`来访问它? (3认同)

小智 5

您可以扩展PageNumberPagination类并重写get_pagination_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
Run Code Online (Sandbox Code Playgroud)

然后在 settings.py 中,添加PageNumberPaginationWithCount类作为默认分页类。

REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'my_project.apps.pagination.PageNumberPaginationWithCount',
    'PAGE_SIZE': 30
}
Run Code Online (Sandbox Code Playgroud)