我正在尝试将分页添加到我的项目中,找不到任何明确的文档或教程。
我有一份办公室名单
模型 Office.py
?>
串行
class Office(Model):
name = CharField(_("name"), default=None, max_length=255, null=True)
email = EmailField(_("email"), default=None, max_length=255, null=True)
description = TextField(_("description"), default=None, null=True)
views.py
class OfficeSerializer(ModelSerializer):
id = IntegerField(read_only=True)
name = CharField(read_only=True)
email = URLField(read_only=True)
description = CharField(read_only=True)
class Meta:
model = Office
fields = ("id", "name", "email", "description")
有关使用分页返回Office列表的任何帮助吗?
答案 0 :(得分:14)
http://www.django-rest-framework.org/api-guide/pagination/
只有在您使用通用符号时才会自动执行分页 视图或视图集。如果您正在使用常规APIView,则需要执行此操作 自己调用分页API以确保返回分页 响应。请参阅mixins.ListModelMixin和的源代码 generics.GenericAPIView类的一个例子。
https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/mixins.py#L35 https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/generics.py#L166
所以我会建议像:
@api_view(["GET"])
@permission_classes((AllowAny,))
def offices(request):
pagination_class = api_settings.DEFAULT_PAGINATION_CLASS
paginator = pagination_class()
queryset = Office.objects.all()
page = paginator.paginate_queryset(queryset, request)
serializer = OfficeSerializer(page, many=True)
return paginator.get_paginated_response(serializer.data)
答案 1 :(得分:0)
http://www.django-rest-framework.org/api-guide/pagination/
GET https://api.example.org/accounts/?limit=100&offset=400
响应:
HTTP 200 OK
{
"count": 1023
"next": "https://api.example.org/accounts/?limit=100&offset=500",
"previous": "https://api.example.org/accounts/?limit=100&offset=300",
"results": [
…
]
}
settings.py
REST_FRAMEWORK = {
'PAGE_SIZE': 10,
'EXCEPTION_HANDLER': 'rest_framework_json_api.exceptions.exception_handler',
'DEFAULT_PAGINATION_CLASS':
'rest_framework_json_api.pagination.PageNumberPagination',
'DEFAULT_PARSER_CLASSES': (
'rest_framework_json_api.parsers.JSONParser',
'rest_framework.parsers.FormParser',
'rest_framework.parsers.MultiPartParser'
),
'DEFAULT_RENDERER_CLASSES': (
'rest_framework_json_api.renderers.JSONRenderer',
'rest_framework.renderers.BrowsableAPIRenderer',
)
}