2. Pages¶
Numbered pages, by default¶
DEFAULT_PAGINATION_CLASS is the library's PageNumberPagination, so every
list is a page - products among them:
{"success": true, "status_code": 200, "message": "Done.",
"data": [...],
"pagination": {"type": "page", "count": 28, "page": 2, "pages": 3, "page_size": 10,
"has_next": true, "has_previous": true}}
There is no next link to follow: the client is on another domain and asks
for ?page=3 itself.
The client chooses the size, under a ceiling¶
The product viewset in step 1 sets two attributes:
| the client asks | it gets |
|---|---|
?page_size=5 |
5 |
?page_size=500 |
20 - the ceiling, not an error |
?page_size=abc, 0, or nothing |
10 - the project's PAGE_SIZE |
pagination.page_size always says the size used. A view that does not allow
it ignores the parameter, and the schema does not offer it.
Orders, as a feed¶
Orders are read newest first, and there are too many to count on every request - a cursor, not a page number:
example/shop/api.py
class OrderViewSet(
EnvelopeMixin,
mixins.CreateModelMixin,
mixins.ListModelMixin,
mixins.RetrieveModelMixin,
viewsets.GenericViewSet[Order],
):
"""Orders, as a feed: newest first, read on by cursor."""
queryset = Order.objects.select_related('product')
serializer_class = OrderSerializer
# drf-parcel: this view pages by cursor; every other by number.
pagination_class = CursorPagination
ordering = '-created_at'
@action(detail=True, methods=['get'])
def receipt(self, request: Request, pk: str) -> Response:
"""A receipt, for a paid order - an error written before the library, unchanged."""
order = self.get_object()
if not order.paid:
raise PaymentRequiredError
return Response({'order': order.pk, 'total': str(order.quantity * order.product.price)})
{"success": true, "status_code": 200, "message": "Done.",
"data": [{"id": 2, "product": 1, "quantity": 2, "paid": false, "created_at": "..."}, ...],
"pagination": {"type": "cursor", "next_cursor": "cD0yMDI2...", "previous_cursor": null,
"page_size": 10, "has_next": true, "has_previous": false}}
The client sends back what it was given - ?cursor=cD0yMDI2... - and never
builds one. has_next is in both kinds, so one "load more" button works with
either, and pagination.type tells them apart.