settings.py
REST_FRAMEWORK = {
'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 1,
}
views.py
class example(GenericAPIView):
queryset = example.objects.all()
serializer_class = ExampleSerializer
def get(self, request, format=None):
query = request.GET.get('name')
if query:
bla = example.objects.filter(name=query)
else:
bla = example.objects.all()
if bla:
serializer = ExampleSerializer(bla, many=True)
return Response(serializer.data)
else:
return Response(status=status.HTTP_404_NOT_FOUND)
现在,如果我转到端点?page = 1,仍然会返回5000条记录。将分页放在我的settings.py中是不够的?我是否需要在视图中添加特定于分页的代码?
答案 0 :(得分:0)
使用自定义分页:
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
def get(self, request, format=None):
query = request.GET.get('name')
limit = request.query_params.get("limit", 5) #objects per page
offset = request.query_params.get("offset", 1) #page no
if query:
bla = example.objects.filter(name=query)
else:
bla = example.objects.all()
if bla:
try:
paginator = Paginator(bla, limit)
except:
paginator = Paginator(bla, 10)
try:
bl = paginator.page(offset)
except PageNotAnInteger:
bl = paginator.page(1)
except EmptyPage:
bl = paginator.page(paginator.num_pages)
count = paginator.count
next = None if not bl.has_next() else bl.next_page_number()
previous = None if not bl.has_previous() else bl.previous_page_number()
serializer = ExampleSerializer(bl, many=True)
data = {"count": count, 'next': next, 'previous': previous, 'results': serializer.data}
return Response(data, status=status.HTTP_200_OK)
else:
return Response(status=status.HTTP_404_NOT_FOUND)