I am trying to add pagination into my project, couldn't find any clear documentation or tutorial.
I have a list of offices
models 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)
Serializer
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")
views.py
@api_view(["GET"])
@permission_classes((AllowAny,))
def offices(request):
instance = Office.objects.filter()[:10]
serializer = OfficeSerializer(instance, many=True)
return Response(serializer.data)
Any help with returning Office list with pagination ?
http://www.django-rest-framework.org/api-guide/pagination/
Pagination is only performed automatically if you're using the generic views or viewsets. If you're using a regular APIView, you'll need to call into the pagination API yourself to ensure you return a paginated response. See the source code for the mixins.ListModelMixin and generics.GenericAPIView classes for an example.
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
so I would suggest something like:
@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)
http://www.django-rest-framework.org/api-guide/pagination/
GET https://api.example.org/accounts/?limit=100&offset=400
Response:
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": [
…
]
}
Example of 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',
)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.