[英]custom pagination of limit and page in Django Rest Framework
I wanted to create custom paginations for this get_queryset.我想为此 get_queryset 创建自定义分页。
get_queryset = Comments.objects.filter(language_post_id=post_in_lang_id,is_post_comment=True).order_by('-created_on')[offset:offset+limit]
I want to change the offset
value whenever the page_no updates.我想在page_no更新时更改
offset
值。 Suppose someone enters page_no=1 , so offset
must be 0 , and when enters 2, so offset
should be 10 , and so on.假设有人输入page_no=1 ,则
offset
必须为0 ,输入 2 时,则offset
应为10 ,以此类推。 Every time page_no updates, it should update the offset
value accordingly.每次page_no更新时,它都应该相应地更新
offset
值。
?page_no=3
:?page_no=3
:get_queryset = Comments.objects.filter(language_post_id=post_in_lang_id,is_post_comment=True).order_by('-created_on')[offset:offset+limit] # [ 20 : 20 + 10 ]
I guess you want to do that in a ListAPIView.我猜你想在 ListAPIView 中这样做。 If that's the case, you can do this really simply using PageNumberPagination .
如果是这种情况,您可以简单地使用PageNumberPagination来做到这一点。
Just define the page size and the page_query_param you want, and the default paginate_queryset()
method will take care of everything for you, you don't have to override it or calculate the offset by yourself.只需定义您想要的页面大小和 page_query_param,默认的
paginate_queryset()
方法将为您处理一切,您不必覆盖它或自己计算偏移量。
# pagination.py
from rest_framework.pagination import PageNumberPagination
class CustomPagination(PageNumberPagination):
# Returns 10 elements per page, and the page query param is named "page_no"
page_size = 10
page_query_param = 'page_no'
# views.py
from rest_framework.generics import ListAPIView
from my_app.pagination import CustomPagination
class MyListView(ListAPIView):
pagination_class = CustomPagination
serializer_class = CommentSerializer
def get_queryset(self):
post_in_lang_id = '1' # Retrieve your post_in_lang_id here
return Comments.objects.filter(language_post_id=post_in_lang_id,is_post_comment=True).order_by('-created_on')
You can also set it as the default paginator by defining DEFAULT_PAGINATION_CLASS
in your settings file.您还可以通过在设置文件中定义
DEFAULT_PAGINATION_CLASS
将其设置为默认分页器。
Here is a mock of what you would get as a result for the first page using this method:这是使用此方法获得的第一页结果的模拟:
{
"count": 20,
"previous": null,
"next": "http://localhost:8000/api/comments/?page_no=2",
"results": [ # List of first 10 elements
{
"id": 1,
[...]
},
[...]
{
"id": 10,
[...]
},
]
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.