gpt4 book ai didi

python - 如何将查询中设置的page_size设置为分页元数据djangorest框架

转载 作者:太空宇宙 更新时间:2023-11-03 21:23:47 28 4
gpt4 key购买 nike

我已经为我的一个应用程序设置了自定义分页,我面临的问题是 page_size 仅显示应用程序中设置的默认值,但不会根据查询参数中发送的值进行更改。我哪里出错了?

class CustomPagination(PageNumberPagination):
page_size = 10
page_size_query_param = 'page_size'

def get_paginated_response(self, data):
return Response({"status": True,
"data": {
'results': data,
"meta": {
'page_count':self.page.paginator.num_pages,
'total_results': self.page.paginator.count,
'current_page_no': self.page.number,
'limit': self.page_size,
'last_page': self.page.has_next()
}}},
status=status.HTTP_200_OK)

即使我将查询参数设置为不同的值,page_size 的输出也始终为 10。例如:如果用户在查询参数中设置page_size =2,则应更改为2。

编辑:

View 代码

class ListPCAPIView(ListAPIView):
serializer_class = ListPCSerializer

def get(self, request):
user = self.request.user
pc = Pc.objects.filter(
user_id=user).order_by('pc_name')
if pc:
page = self.paginate_queryset(pc)
if page is not None:
serializer = self.get_serializer(page, many=True)
return self.get_paginated_response(serializer.data)
else:
raise CustomException(
detail="pc list is empty.",
status_code=status.HTTP_400_BAD_REQUEST)

最佳答案

有一种方法可以帮助您实现这一目标。 get_page_size(request) 是的,您需要传入原始请求。幸运的是,您可以通过 self.request

获取它
def get_paginated_response(self, data):
print(self.get_page_size(self.request))
....

此外,获取当前页面大小和记录数所需的总页数可以执行以下操作。

import math
num_of_pages = math.ceil(self.page.paginator.count / self.get_page_size(self.request))

完整示例

分页.py

import math

from dataclasses import dataclass
from dataclasses_json import dataclass_json
from typing import Any
from rest_framework import pagination
from rest_framework.response import Response


@dataclass_json
@dataclass
class PaginationResponse:
count: int
next: int
previous: int
page_number: int
num_of_pages: int
page_size: int
results: Any


class NumberPagination(pagination.PageNumberPagination):
page_size_query_param = 'page_size'
max_page_size = 100

# Path Query parameter ?page=1&page_size=5
def get_paginated_response(self, data):
pagination_response = PaginationResponse(
count=self.page.paginator.count,
next=self.page.next_page_number() if self.page.has_next() else None,
previous=self.page.previous_page_number() if self.page.has_previous() else None,
page_number=self.page.number,
num_of_pages=math.ceil(self.page.paginator.count / self.get_page_size(self.request)),
results=data,
page_size=self.get_page_size(self.request),
).to_dict()

return Response(pagination_response)

settings.py

REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': '<REGISTER-NumberPagination-CLASS-HERE>',
'PAGE_SIZE': 10,
...
}

希望这有帮助

关于python - 如何将查询中设置的page_size设置为分页元数据djangorest框架,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54006820/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com