Django rest 如何使用 PageNumberPagination 进行分页
Django rest how to do pagination with PageNumberPagination
我写了下面的代码。但是当我转到 url posts?page=1
时,它仍然显示所有 Post 模型对象。我该怎么办?
settings.py
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 10
}
ursl.py
path('posts', views.posts_view, name='posts_view')
views.py
@api_view(['GET'])
def posts_view(request):
posts = Post.objects.all()
serializer = PostSerializer(posts, many=True)
return Response(serializer.data)
您正在编写一个基于函数的视图,因此您需要手动完成所有操作。如果可能,您应该依赖 provided generic base api views 而不是尝试 re-write this:
class PostView(generics.ListAPIView):
queryset = Post.objects.all()
serializer_class = PostSerializer
path('posts', PostView.as_view(), name='posts_view')
要手动完成,您将需要创建和调用分页,就像基础 类 做的那样:
def my_view(request):
qs = Post.objects.all()
pagination = PageNumberPagination()
page = pagination.paginate_queryset(qs, request)
serializer = PostSerializer(page, many=True)
return pagination.get_paginated_response(
serializer.data
)
我写了下面的代码。但是当我转到 url posts?page=1
时,它仍然显示所有 Post 模型对象。我该怎么办?
settings.py
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 10
}
ursl.py
path('posts', views.posts_view, name='posts_view')
views.py
@api_view(['GET'])
def posts_view(request):
posts = Post.objects.all()
serializer = PostSerializer(posts, many=True)
return Response(serializer.data)
您正在编写一个基于函数的视图,因此您需要手动完成所有操作。如果可能,您应该依赖 provided generic base api views 而不是尝试 re-write this:
class PostView(generics.ListAPIView):
queryset = Post.objects.all()
serializer_class = PostSerializer
path('posts', PostView.as_view(), name='posts_view')
要手动完成,您将需要创建和调用分页,就像基础 类 做的那样:
def my_view(request):
qs = Post.objects.all()
pagination = PageNumberPagination()
page = pagination.paginate_queryset(qs, request)
serializer = PostSerializer(page, many=True)
return pagination.get_paginated_response(
serializer.data
)