Issue
I have a function based Django API as shown in this sample:
@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))
But I keep getting this error:
AttributeError: 'PageNumberPagination' object has no attribute 'page'
I tried setting
paginator.page_query_param = page_query_param
But still same problem. Please advise of how to fix.
Solution
It is likely more effective to use a ListView
, not only this will remove a lot of boilerplate code, but also is likely less error prone. You can just subclass the paginator to your own:
class MyPaginator(PageNumberPagination):
page_size = 100
page_size_query_param = 'page_size'
max_page_size = 1000
Then in the ListView
, we can make use of the MyPaginator
:
from rest_framework import generics
class DataListView(generics.ListAPIView):
queryset = Data.objects.all()
serializer_class = dataIdSerializer
pagination_class = MyPaginator
def get_queryset(self, *args, **kwargs):
dataId = self.request.GET['dataId']
super().get_queryset(*args, **kwargs).filter(
# …
)
Here you can filter the queryset in the get_queryset
method to only use Data
objects that satisfy a given condition.
In the urls, you can then finally link it with .as_view()
:
urlpatterns = [
path('/findData', DataListView.as_view())
]
Answered By - Willem Van Onsem
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.