我正在使用 Django REST Framework,我需要根据随请求提供的 GET 参数对列表进行分页。
我知道我可以在设置中设置 'PAGINATE_BY': 10
,但是我想让调用者在发出请求时指定他们想要分页的数字。
我目前有以下序列化器:
from api.models import Countries
from rest_framework import serializers
class CountrySerializer(serializers.Serializer):
country_geoname_id = serializers.CharField(required=True)
country_code = serializers.CharField(source="iso", max_length=2L, required=True)
country_name = serializers.CharField(max_length=64L, required=True)
def transform_iso(self, obj, value):
return "country_code"
我尝试了以下 View :
@api_view(['GET'])
def country_list(request):
"""
List all countries
"""
if request.method == 'GET':
queryset = Countries.objects.all()
serializer = CountrySerializer(queryset, many=True, data=request.DATA)
paginate_by = request.GET.get('limit', 10)
return Response(serializer.data)
但是我觉得我遗漏了一些东西,而且我一直无法从文档中弄清楚。
我应该在序列化程序中还是在 View 中进行分页?
提前致谢。
最佳答案
让我们分解问题:
您需要创建一个允许用户定义页面大小的分页方法:
如
PageNumberPagination
中所述在 DRF 文档中,您可以通过覆盖page_size_query_param
来定义参数名称:If set, this is a string value indicating the name of a query parameter that allows the client to set the page size on a per-request basis. Defaults to
None
, indicating that the client may not control the requested page size.您可以通过以下方式之一实现:
在
settings.py
中添加以下内容:REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 10, 'PAGINATE_BY_PARAM': 'page_size' }
或者您可以创建自定义分页类并在其中覆盖您的设置:
from rest_framework.pagination import PageNumberPagination class MyPagination(PageNumberPagination): page_size = 10 page_size_query_param = 'page_size'
最后,您需要定义要在 View 函数中使用的分页类。
以下示例只需将
paginator
变量的值更改为PageNumberPaginator
或MyPaginator
即可适用于上述任一情况>:from rest_framework.pagination import PageNumberPagination @api_view(['GET']) def country_list(request): """ List all countries """ if request.method == 'GET': paginator = PageNumberPagination() queryset = Countries.objects.all() context = paginator.paginate_queryset(queryset, request) serializer = CountrySerializer(context, many=True) return paginator.get_paginated_response(serializer.data)
现在您有了基于函数的 View ,其中包含分页和用于更改页面大小的查询参数。
关于python - Django Rest Framework 按指定的 GET 参数分页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19928382/