File: pagination.md

package info (click to toggle)
strawberry-graphql-django 0.62.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 1,968 kB
  • sloc: python: 27,530; sh: 17; makefile: 16
file content (317 lines) | stat: -rw-r--r-- 7,282 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
---
title: Pagination
---

# Pagination

## Default pagination

An interface for limit/offset pagination can be use for basic pagination needs:

```python title="types.py"
@strawberry_django.type(models.Fruit, pagination=True)
class Fruit:
    name: auto


@strawberry.type
class Query:
    fruits: list[Fruit] = strawberry_django.field()
```

Would produce the following schema:

```graphql title="schema.graphql"
type Fruit {
  name: String!
}

input OffsetPaginationInput {
  offset: Int! = 0
  limit: Int = null
}

type Query {
  fruits(pagination: OffsetPaginationInput): [Fruit!]!
}
```

And can be queried like:

```graphql title="schema.graphql"
query {
  fruits(pagination: { offset: 0, limit: 2 }) {
    name
  }
}
```

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:

```python title="types.py"
@strawberry_django.type(models.Fruit)
class Fruit:
    name: auto


@strawberry.type
class Query:
    fruits: list[Fruit] = strawberry_django.field(pagination=True)
```

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](./settings.md) 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:

```python
@strawberry.input
def MyOffsetPaginationInput(OffsetPaginationInput):
    limit: int = 250


# Pass it to the pagination argument when defining the type
@strawberry_django.type(models.Fruit, pagination=MyOffsetPaginationInput)
class Fruit:
    ...


@strawberry.type
class Query:
    # Or pass it to the pagination argument when defining the field
    fruits: list[Fruit] = strawberry_django.field(pagination=MyOffsetPaginationInput)
```

## 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.

```python title="types.py"
from strawberry_django.pagination import OffsetPaginated


@strawberry_django.type(models.Fruit)
class Fruit:
    name: auto


@strawberry.type
class Query:
    fruits: OffsetPaginated[Fruit] = strawberry_django.offset_paginated()
```

Would produce the following schema:

```graphql title="schema.graphql"
type Fruit {
  name: String!
}

type PaginationInfo {
  limit: Int = null
  offset: Int!
}

type FruitOffsetPaginated {
  pageInfo: PaginationInfo!
  totalCount: Int!
  results: [Fruit]!
}

input OffsetPaginationInput {
  offset: Int! = 0
  limit: Int = null
}

type Query {
  fruits(pagination: OffsetPaginationInput): [FruitOffsetPaginated!]!
}
```

Which can be queried like:

```graphql title="schema.graphql"
query {
  fruits(pagination: { offset: 0, limit: 2 }) {
    totalCount
    pageInfo {
      limit
      offset
    }
    results {
      name
    }
  }
}
```

> [!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](./ordering.md) to it. This can be achieved with:

```python title="types.py"

@strawberry_django.type(models.Fruit)
class Fruit:
    name: auto
    price: auto


@strawberry_django.order(models.Fruit)
class FruitOrder:
    name: auto
    price: auto


@strawberry.type
class Query:
    @strawberry_django.offset_paginated(OffsetPaginated[Fruit], order=order)
    def fruits(self, only_available: bool = True) -> QuerySet[Fruit]:
        queryset = models.Fruit.objects.all()
        if only_available:
            queryset = queryset.filter(available=True)

        return queryset
```

This would produce the following schema:

```graphql title="schema.graphql"
type Fruit {
  name: String!
  price: Decimal!
}

type FruitOrder {
  name: Ordering
  price: Ordering
}

type PaginationInfo {
  limit: Int!
  offset: Int!
}

type FruitOffsetPaginated {
  pageInfo: PaginationInfo!
  totalCount: Int!
  results: [Fruit]!
}

input OffsetPaginationInput {
  offset: Int! = 0
  limit: Int = null
}

type Query {
  fruits(
    onlyAvailable: Boolean! = true
    pagination: OffsetPaginationInput
    order: FruitOrder
  ): [FruitOffsetPaginated!]!
}
```

### 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:

```python title="types.py"
from strawberry_django.pagination import OffsetPaginated


@strawberry_django.type(models.Fruit)
class Fruit:
    name: auto
    price: auto


@strawberry.type
class FruitOffsetPaginated(OffsetPaginated[Fruit]):
    @strawberry_django.field
    def average_price(self) -> Decimal:
        if self.queryset is None:
            return Decimal(0)

        return self.queryset.aggregate(Avg("price"))["price__avg"]

    @strawberry_django.field
    def paginated_average_price(self) -> Decimal:
        paginated_queryset = self.get_paginated_queryset()
        if paginated_queryset is None:
            return Decimal(0)

        return paginated_queryset.aggregate(Avg("price"))["price__avg"]


@strawberry.type
class Query:
    fruits: FruitOffsetPaginated = strawberry_django.offset_paginated()
```

Would produce the following schema:

```graphql title="schema.graphql"
type Fruit {
  name: String!
}

type PaginationInfo {
  limit: Int = null
  offset: Int!
}

type FruitOffsetPaginated {
  pageInfo: PaginationInfo!
  totalCount: Int!
  results: [Fruit]!
  averagePrice: Decimal!
  paginatedAveragePrice: Decimal!
}

input OffsetPaginationInput {
  offset: Int! = 0
  limit: Int = null
}

type Query {
  fruits(pagination: OffsetPaginationInput): [FruitOffsetPaginated!]!
}
```

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`: The `OffsetPaginationInput` object, with the `offset` and `limit` 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, pagination, **kwargs)`: The classmethod that
  strawberry-django calls to create an instance of the `OffsetPaginated` class/subclass.

## Cursor pagination (aka Relay style pagination)

Another option for pagination is to use a
[relay style cursor pagination](https://graphql.org/learn/pagination). For this,
you can leverage the [relay integration](./relay.md) provided by strawberry
to create a relay connection.