Django REST 框架中基于@api_view的视图使用分页

参考:https://riptutorial.com/django-rest-framework/example/31648/-intermediate--pagination-on-a-function-based-view

 

代码:

from rest_framework.pagination import PageNumberPagination


@api_view(['GET',])
def my_function_based_list_view(request):
    paginator = PageNumberPagination()
    query_set = MyModel.objects.all()
    context = paginator.paginate_queryset(query_set, request)
    serializer = MyModelSerializer(context, many=True)
    return paginator.get_paginated_response(serializer.data)

  

如果需要使用自定义的分页,更改panigator的初始化函数:

paginator = MyCustomPagination()

  

posted @ 2024-09-27 19:47  walteronly1  阅读(5)  评论(0编辑  收藏  举报