Django 中的列表分页
List pagination in Django
我想对图书列表进行分页。 api终点是这样的/books?page=num&size=num
所以页数和加载多少本书将是变量。
我的回复应该是这样的:
{
pagesnum= totalpages
booksnum=totalbooks
books=
[ {detailsofbook1},
{...},
{...}
]
}
我的代码:
网址格式:
path('api/books?page=<int:page>&size=<int:size>/',BookView.as_view()),
views.py
class BookView(APIView):
http_method_names = ['get']
permission_classes = (permissions.IsAuthenticated,)
def index(request):
books = Books.objects.all()
books_per_page= request.GET.get('size')
book_paginator = Paginator(books, books_per_page)
page_num = request.GET.get('page')
page = book_paginator.get_page(page_num)
context = {
'count': book_paginator.count(),
'page': page
queryset =Books.ojects.all()
}
return JsonResponse(context, status=200)
This implementation doesn't work. First of all something is wrong probably with the url it doesnt seem to understand the variables. Or is something else wrong with my code?
page
和 size
是 query parameters
,所以你通过访问 request.query_params
得到它们,所以它应该像
books_per_page= request.query_params.get('size') # or request.query_params['size]
page_num = request.query_params.get('page')
另外,我对 index()
有点困惑我认为你的代码应该在 get(self, request, *args, **kwargs)
最后一件事是您可以在 DRF 中使用分页,see
我想对图书列表进行分页。 api终点是这样的/books?page=num&size=num
所以页数和加载多少本书将是变量。
我的回复应该是这样的:
{
pagesnum= totalpages
booksnum=totalbooks
books=
[ {detailsofbook1},
{...},
{...}
]
}
我的代码:
网址格式:
path('api/books?page=<int:page>&size=<int:size>/',BookView.as_view()),
views.py
class BookView(APIView):
http_method_names = ['get']
permission_classes = (permissions.IsAuthenticated,)
def index(request):
books = Books.objects.all()
books_per_page= request.GET.get('size')
book_paginator = Paginator(books, books_per_page)
page_num = request.GET.get('page')
page = book_paginator.get_page(page_num)
context = {
'count': book_paginator.count(),
'page': page
queryset =Books.ojects.all()
}
return JsonResponse(context, status=200)
This implementation doesn't work. First of all something is wrong probably with the url it doesnt seem to understand the variables. Or is something else wrong with my code?
page
和 size
是 query parameters
,所以你通过访问 request.query_params
得到它们,所以它应该像
books_per_page= request.query_params.get('size') # or request.query_params['size]
page_num = request.query_params.get('page')
另外,我对 index()
有点困惑我认为你的代码应该在 get(self, request, *args, **kwargs)
最后一件事是您可以在 DRF 中使用分页,see