django

pagination

베스트오버 2023. 7. 7.

Django는 DRF에서 이전/다음 링크를 이용하여 관리하는데 도움을 주는 pagintion 기능을 이미 제공하고 있습니다.

 

settings.py

REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 100
}

 

page

- 몇 번째 페이지인지 표시

- 1부터 표시

 

page_size

 - 한 페이지에 몇 개의 레코드를 보여줄 지 표시

 

요청

GET https://api.example.org/accounts/?page=4

응답

HTTP 200 OK
{
    "count": 1023,
    "next": "https://api.example.org/accounts/?page=5",
    "previous": "https://api.example.org/accounts/?page=3",
    "results": [
       …
    ]
}

 

 

from rest_framework.pagination import PageNumberPagination

class ConvertedFilesView(APIView):
    pagination_class = PageNumberPagination()

    def get_user_converted_files(self, user):
        files = SeparationResult.objects.filter(user=user).order_by('-created_at')
        page = self.pagination_class.paginate_queryset(files, self.request)
        if page is not None:
            serializer = SeparationResultSerializer(page, many=True)
            return self.pagination_class.get_paginated_response(serializer.data)
        serializer = SeparationResultSerializer(files, many=True)
        return serializer.data

페이지가 있다면 지정 한 수만 보여주고 다음 링크를 보내줍니다.

댓글