Pagination
Default pagination
An interface for limit/offset pagination can be use for basic pagination needs:
Would produce the following schema:
And can be queried like:
The pagination
argument can be given to the type, which will enforce the pagination
argument every time the field is annotated as a list, but you can also give it directly
to the field for more control, like:
Which will produce the exact same schema.
Default limit for pagination
The default limit for pagination is set to 100
. This can be changed in the
strawberry django settings to increase or decrease that number,
or even set to None
to set it to unlimited.
To configure it on a per field basis, you can define your own OffsetPaginationInput
subclass and modify its default value, like:
OffsetPaginated Generic
For more complex pagination needs, you can use the OffsetPaginated
generic, which alongside
the pagination
argument, will wrap the results in an object that contains the results
and the pagination information, together with the totalCount
of elements excluding pagination.
Would produce the following schema:
Which can be queried like:
Note
OffsetPaginated follow the same rules for the default pagination limit, and can be configured in the same way as explained above.
Customizing queryset resolver
It is possible to define a custom resolver for the queryset to either provide a custom queryset for it, or even to receive extra arguments alongside the pagination arguments.
Suppose we want to pre-filter a queryset of fruits for only available ones, while also adding ordering to it. This can be achieved with:
This would produce the following schema:
Customizing the pagination
Like other generics, OffsetPaginated
can be customized to modify its behavior or to
add extra functionality in it. For example, suppose we want to add the average
price of the fruits in the pagination:
Would produce the following schema:
The following attributes/methods can be accessed in the OffsetPaginated
class:
-
queryset
: The queryset original queryset with any filters/ordering applied, but not paginated yet -
pagination
: TheOffsetPaginationInput
object, with theoffset
andlimit
for pagination -
get_total_count()
: Returns the total count of elements in the queryset without pagination -
get_paginated_queryset()
: Returns the queryset with pagination applied -
resolve_paginated(queryset, *, info, pagiantion, **kwargs)
: The classmethod that strawberry-django calls to create an instance of theOffsetPaginated
class/subclass.
Cursor pagination (aka Relay style pagination)
Another option for pagination is to use a relay style cursor pagination . For this, you can leverage the relay integration provided by strawberry to create a relay connection.