Django provides a few classes that help you manage paginated data – that is, data that’s split across several pages, with “Previous/Next” links.
Django는 페이지화된 데이터, 즉 "이전/다음" 링크를 사용하여 여러 페이지로 분할된 데이터를 관리하는 데 도움이 되는 몇 가지 클래스를 제공합니다.
— Django documentation
# views.py
class PostListAPIView(ListAPIView):
queryset = Post.objects.all()
serializer_class = PostListSerializer
# serializers.py
class PostListSerializer(serializers.ModelSerializer):
class Meta:
model = Post
fields = ['id', 'title', 'image', 'like','category']
# views.py
from rest_framework.pagination import PageNumberPagination
class PostPageNumberPagination(PageNumberPagination):
page_size = 3
class PostListAPIView(ListAPIView):
queryset = Post.objects.all()
serializer_class = PostListSerializer
pagination_class = PostPageNumberPagination
from collections import OrderedDict
class PostPageNumberPagination(PageNumberPagination):
page_size = 3
def get_paginated_response(self, data):
return Response(OrderedDict([
('postList', data),
('pageCnt', self.page.paginator.num_pages),
('curPage', self.page.number),
]))
page.paginator.num_pages
, page.number
코드에 대한 부분은 Django 공식문서 참고.
class PostListSerializer(serializers.ModelSerializer):
category = serializers.CharField(source='category.name')
class Meta:
model = Post
fields = ['id', 'title', 'image', 'like','category']
class PostListAPIView(ListAPIView):
queryset = Post.objects.all()
serializer_class = PostListSerializer
pagination_class = PostPageNumberPagination
def get_serializer_context(self):
return {
'request': None, # None이 아닌 경우에 full url 표시
'format': self.format_kwarg,
'view': self
}
참고
FileField(Field): def to_representation(self, value)
class GenericAPIView(views.APIView): def get_serializer_context(self)