gpt4 book ai didi

Django Rest 'PageNumberPagination'对象没有属性 'page'错误

转载 作者:行者123 更新时间:2023-12-05 02:54:35 24 4
gpt4 key购买 nike

我有一个基于函数的 Django API,如本示例所示:

@api_view(['GET'])
def findData(request):
dataId = request.GET['dataId']
page_query_param = 'page'
page_size = request.GET['page_size']
paginator = PageNumberPagination()
paginator.page_size = page_size
paginator.page_query_param = page_query_param
qry_set = Data.objects.all()
serializer = dataIdSerializer(qry_set, many=True)
theData= serializer.data
return Response(paginator.get_paginated_response(theData))

但我一直收到这个错误:

AttributeError: 'PageNumberPagination' object has no attribute 'page'

我试过设置

paginator.page_query_param = page_query_param

还是一样的问题。请告知如何修复。

最佳答案

问题是当调用 .paginate_queryset() 时,page 设置在 PageNumberPagination 上。

因此,您需要在您的paginator 上调用.paginate_queryset() 并传递querysetrequest.

当您实例化序列化器时,传递通过调用 .paginate_queryset() 而不是 qry_set 获得的结果

完成后,DRF 将抛出另一个异常,因为您将 paginator.get_paginated_response(theData) 放入 Response 中。要解决这个问题,只需返回 paginator.get_paginated_response(theData)

最后您的代码将如下所示:

def findData(request):
dataId = request.GET['dataId']
page_query_param = 'page'
page_size = request.GET['page_size']
paginator = PageNumberPagination()
paginator.page_size = page_size
paginator.page_query_param = page_query_param
qry_set = Data.objects.all()
p = paginator.paginate_queryset(queryset=qry_set, request=request) # change 1
serializer = dataIdSerializer(p, many=True) # change 2
theData= serializer.data
return paginator.get_paginated_response(theData) # change 3

关于Django Rest 'PageNumberPagination'对象没有属性 'page'错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61738832/

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