File: optimizer.md

package info (click to toggle)
strawberry-graphql-django 0.78.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 2,624 kB
  • sloc: python: 31,895; makefile: 24; sh: 21
file content (577 lines) | stat: -rw-r--r-- 18,618 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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
---
title: Query Optimizer
---

# Query Optimizer

## Features

The query optimizer is a must-have extension for improved performance of your schema.
What it does:

1. Call [QuerySet.select_related()](https://docs.djangoproject.com/en/4.2/ref/models/querysets/#select-related)
   on all selected foreign key relations by the query to avoid requiring an extra query to retrieve those
2. Call [QuerySet.prefetch_related()](https://docs.djangoproject.com/en/4.2/ref/models/querysets/#prefetch-related)
   on all selected many-to-one/many-to-many relations by the query to avoid requiring an extra query to retrieve those.
3. Call [QuerySet.only()](https://docs.djangoproject.com/en/4.2/ref/models/querysets/#only)
   on all selected fields to reduce the database payload and only requesting what is actually being
   selected
4. Call [QuerySet.annotate()](https://docs.djangoproject.com/en/4.2/ref/models/querysets/#annotate)
   to support any passed annotations
   of [Query Expressions](https://docs.djangoproject.com/en/4.2/ref/models/expressions/).

Those are specially useful to avoid some common GraphQL pitfalls, like the famous `n+1` issue.

## Enabling the extension

The automatic optimization can be enabled by adding the `DjangoOptimizerExtension`
to your strawberry's schema config.

```python title="schema.py"
import strawberry
from strawberry_django.optimizer import DjangoOptimizerExtension

schema = strawberry.Schema(
    Query,
    extensions=[
        # other extensions...
        DjangoOptimizerExtension,
    ]
)
```

### Extension Parameters

The extension accepts several parameters to customize its behavior:

```python
DjangoOptimizerExtension(
    enable_only_optimization=True,           # Enable QuerySet.only() optimization
    enable_select_related_optimization=True, # Enable QuerySet.select_related() optimization
    enable_prefetch_related_optimization=True, # Enable QuerySet.prefetch_related() optimization
    enable_annotate_optimization=True,       # Enable QuerySet.annotate() optimization
    enable_nested_relations_prefetch=True,   # Enable prefetch of nested relations
    prefetch_custom_queryset=False,          # Use default manager instead of base manager
)
```

| Parameter                              | Default | Description                                                    |
| -------------------------------------- | ------- | -------------------------------------------------------------- |
| `enable_only_optimization`             | `True`  | Enable `QuerySet.only()` to fetch only requested fields        |
| `enable_select_related_optimization`   | `True`  | Enable `QuerySet.select_related()` for FK relations            |
| `enable_prefetch_related_optimization` | `True`  | Enable `QuerySet.prefetch_related()` for M2M/reverse relations |
| `enable_annotate_optimization`         | `True`  | Enable `QuerySet.annotate()` for annotated fields              |
| `enable_nested_relations_prefetch`     | `True`  | Enable prefetch of nested relations with filters/pagination    |
| `prefetch_custom_queryset`             | `False` | Use default manager instead of base manager for prefetches     |

> [!NOTE]
> Setting `prefetch_custom_queryset=True` is useful when using `InheritanceManager` from django-model-utils,
> as it ensures the correct manager is used for polymorphic queries.

## Usage

The optimizer will try to optimize all types automatically by introspecting it.
Consider the following example:

```python title="models.py"
class Artist(models.Model):
    name = models.CharField()


class Album(models.Model):
    name = models.CharField()
    release_date = models.DateTimeField()
    artist = models.ForeignKey("Artist", related_name="albums")


class Song(models.Model):
    name = model.CharField()
    duration = models.DecimalField()
    album = models.ForeignKey("Album", related_name="songs")
```

```python title="types.py"
from strawberry import auto
import strawberry_django

@strawberry_django.type(Artist)
class ArtistType:
    name: auto
    albums: list["AlbumType"]
    albums_count: int = strawberry_django.field(annotate=Count("albums"))


@strawberry_django.type(Album)
class AlbumType:
    name: auto
    release_date: auto
    artist: ArtistType
    songs: list["SongType"]


@strawberry_django.type(Song)
class SongType:
    name: auto
    duration: auto
    album_type: AlbumType


@strawberry.type
class Query:
    artist: Artist = strawberry_django.field()
    songs: list[SongType] = strawberry_django.field()
```

Querying for `artist` and `songs` like this:

```graphql title="schema.graphql"
query {
  artist {
    id
    name
    albums {
      id
      name
      songs {
        id
        name
      }
    }
    albumsCount
  }
  song {
    id
    album {
      id
      name
      artist {
        id
        name
        albums {
          id
          name
          release_date
        }
      }
    }
  }
}
```

Would produce an ORM query like this:

```python
# For "artist" query
Artist.objects.all().only("id", "name").prefetch_related(
    Prefetch(
        "albums",
        queryset=Album.objects.all().only("id", "name").prefetch_related(
            Prefetch(
               "songs",
               Song.objects.all().only("id", "name"),
            )
        )
    ),
).annotate(
    albums_count=Count("albums")
)

# For "songs" query
Song.objects.all().only(
    "id",
    "album",
    "album__id",
    "album__name",
    "album__release_date",  # Note about this below
    "album__artist",
    "album__artist__id",
).select_related(
    "album",
    "album__artist",
).prefetch_related(
    Prefetch(
       "album__artist__albums",
        Album.objects.all().only("id", "name", "release_date"),
    )
)
```

> [!NOTE]
> Even though `album__release_date` field was not selected here, it got selected
> in the prefetch query later. Since Django caches known objects, we have to select it here or
> else it would trigger extra queries latter.

## Optimization hints

Sometimes you will have a custom resolver which cannot be automatically optimized
by the extension. Take this for example:

```python title="models.py"
class OrderItem(models.Model):
    price = models.DecimalField()
    quantity = models.IntegerField()

    @property
    def total(self) -> decimal.Decimal:
        return self.price * self.quantity
```

```python title="types.py"
from strawberry import auto
import strawberry_django

@strawberry_django.type(models.OrderItem)
class OrderItem:
    price: auto
    quantity: auto
    total: auto
```

In this case, if only `total` is requested it would trigger an extra query for
both `price` and `quantity` because both had their value retrievals
[defered](https://docs.djangoproject.com/en/4.2/ref/models/querysets/#django.db.models.query.QuerySet.defer)
by the optimizer.

A solution in this case would be to "tell the optimizer" how to optimize that field:

```python title="types.py"
from strawberry import auto
import strawberry_django

@strawberry_django.type(models.OrderItem)
class OrderItem:
    price: auto
    quantity: auto
    total: auto = strawberry_django.field(
        only=["price", "quantity"],
    )
```

Or if you are using a custom resolver:

```python title="types.py"
import decimal

from strawberry import auto
import strawberry_django

@strawberry_django.type(models.OrderItem)
class OrderItem:
    price: auto
    quantity: auto

    @strawberry_django.field(only=["price", "quantity"])
    def total(self, root: models.OrderItem) -> decimal.Decimal:
        return root.price * root.quantity  # or root.total directly
```

The following options are accepted for optimizer hints:

- `only`: a list of fields in the same format as accepted by
  [QuerySet.only()](https://docs.djangoproject.com/en/4.2/ref/models/querysets/#only)
- `select_related`: a list of relations to join using
  [QuerySet.select_related()](https://docs.djangoproject.com/en/4.2/ref/models/querysets/#select-related)
- `prefetch_related`: a list of relations to prefetch using
  [QuerySet.prefetch_related()](https://docs.djangoproject.com/en/4.2/ref/models/querysets/#prefetch-related).
  The options here are strings or a callable in the format of `Callable[[Info], Prefetch]`
  (e.g. `prefetch_related=[lambda info: Prefetch(...)]`)
- `annotate`: a dict of expressions to annotate using
  [QuerySet.annotate()](https://docs.djangoproject.com/en/4.2/ref/models/querysets/#annotate).
  The keys of this dict are strings,
  and each value is a [Query Expression](https://docs.djangoproject.com/en/4.2/ref/models/expressions/)
  or a callable in the format of `Callable[[Info], BaseExpression]`
  (e.g. `annotate={"total": lambda info: Sum(...)}`)

## Optimization hints on model (ModelProperty)

It is also possible to include type hints directly in the models' `@property`
to allow it to be resolved with `auto`, while the GraphQL schema doesn't have
to worry about its internal logic.

For that this integration provides 2 decorators that can be used:

- `strawberry_django.model_property`: similar to `@property` but accepts optimization hints
- `strawberry_django.cached_model_property`: similar to `@cached_property` but accepts
  optimization hints

The example in the previous section could be written using `@model_property` like this:

```python title="models.py"
from strawberry_django.descriptors import model_property

class OrderItem(models.Model):
    price = models.DecimalField()
    quantity = models.IntegerField()

    @model_property(only=["price", "quantity"])
    def total(self) -> decimal.Decimal:
        return self.price * self.quantity
```

```python title="types.py"
from strawberry import auto
import strawberry_django

@strawberry_django.type(models.OrderItem)
class OrderItem:
    price: auto
    quantity: auto
    total: auto
```

`total` now will be properly optimized since it points to a `@model_property`
decorated attribute, which contains the required information for optimizing it.

## Optimizing polymorphic queries

The optimizer has dedicated support for polymorphic queries, that is, fields which return an interface.
The optimizer will handle optimizing any subtypes of the interface as necessary. This is supported on top level queries
as well as relations between models.
See the following sections for how this interacts with your models.

### Using Django Polymorphic

If you are already using the [Django Polymorphic](https://django-polymorphic.readthedocs.io/en/stable/) library,
polymorphic queries work out of the box.

```python title="models.py"
from django.db import models
from polymorphic.models import PolymorphicModel

class Project(PolymorphicModel):
    topic = models.CharField(max_length=255)

class ResearchProject(Project):
    supervisor = models.CharField(max_length=30)

class ArtProject(Project):
    artist = models.CharField(max_length=30)
```

```python title="types.py"
import strawberry
import strawberry_django
from . import models


@strawberry_django.interface(models.Project)
class ProjectType:
    topic: strawberry.auto


@strawberry_django.type(models.ResearchProject)
class ResearchProjectType(ProjectType):
    supervisor: strawberry.auto


@strawberry_django.type(models.ArtProject)
class ArtProjectType(ProjectType):
    artist: strawberry.auto


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

The `projects` field will return either ResearchProjectType or ArtProjectType, matching on whether it is a
ResearchProject or ArtProject. The optimizer will make sure to only select those fields from subclasses which are
requested in the GraphQL query in the same way that it does normally.

> [!WARNING]
> The optimizer does not filter your QuerySet and Django will return
> all instances of your model, regardless of whether their type exists in your GraphQL schema or not.
> Make sure you have a corresponding type for every model subclass or add a `get_queryset` method to your
> GraphQL interface type to filter out unwanted subtypes.
> Otherwise you might receive an error like
> `Abstract type 'ProjectType' must resolve to an Object type at runtime for field 'Query.projects'.`

### Using Model-Utils InheritanceManager

Models using `InheritanceManager` from [django-model-utils](https://django-model-utils.readthedocs.io/en/latest/)
are also supported.

```python title="models.py"
from django.db import models
from model_utils.managers import InheritanceManager

class Project(models.Model):
    topic = models.CharField(max_length=255)

    objects = InheritanceManager()

class ResearchProject(Project):
    supervisor = models.CharField(max_length=30)

class ArtProject(Project):
    artist = models.CharField(max_length=30)
```

```python title="types.py"
import strawberry
import strawberry_django
from . import models


@strawberry_django.interface(models.Project)
class ProjectType:
    topic: strawberry.auto


@strawberry_django.type(models.ResearchProject)
class ResearchProjectType(ProjectType):
    supervisor: strawberry.auto


@strawberry_django.type(models.ArtProject)
class ArtProjectType(ProjectType):
    artist: strawberry.auto


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

The `projects` field will return either ResearchProjectType or ArtProjectType, matching on whether it is a
ResearchProject or ArtProject. The optimizer automatically calls `select_subclasses`, passing in any subtypes present
in your schema.

> [!WARNING]
> The optimizer does not filter your QuerySet and Django will return
> all instances of your model, regardless of whether their type exists in your GraphQL schema or not.
> Make sure you have a corresponding type for every model subclass or add a `get_queryset` method to your
> GraphQL interface type to filter out unwanted subtypes.
> Otherwise you might receive an error like
> `Abstract type 'ProjectType' must resolve to an Object type at runtime for field 'Query.projects'.`

> [!NOTE]
> If you have polymorphic relations (as in: a field that points to a model with subclasses), you need to make sure
> the manager being used to look up the related model is an `InheritanceManager`.
> Strawberry Django uses the model's [base manager](https://docs.djangoproject.com/en/5.1/topics/db/managers/#base-managers)
> by default, which is different from the standard `objects`.
> Either change your base manager to also be an `InheritanceManager` or set Strawberry Django to use the default
> manager: `DjangoOptimizerExtension(prefetch_custom_queryset=True)`.

### Custom polymorphic solution

The optimizer also supports polymorphism even if your models are not polymorphic.
`resolve_type` in the GraphQL interface type is used to tell GraphQL the actual type that should be used.

```python title="models.py"
from django.db import models

class Project(models.Model):
    topic = models.CharField(max_length=255)
    supervisor = models.CharField(max_length=30)
    artist = models.CharField(max_length=30)

```

```python title="types.py"
import strawberry
import strawberry_django
from . import models


@strawberry_django.interface(models.Project)
class ProjectType:
    topic: strawberry.auto

    @classmethod
    def resolve_type(cls, value, info, parent_type) -> str:
        if not isinstance(value, models.Project):
            raise TypeError()
        if value.artist:
            return 'ArtProjectType'
        if value.supervisor:
            return 'ResearchProjectType'
        raise TypeError()

    @classmethod
    def get_queryset(cls, qs, info):
        return qs


@strawberry_django.type(models.ResearchProject)
class ResearchProjectType(ProjectType):
    supervisor: strawberry.auto


@strawberry_django.type(models.ArtProject)
class ArtProjectType(ProjectType):
    artist: strawberry.auto


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

> [!WARNING]
> Make sure to add `get_queryset` to your interface type, to force the optimizer to use
> `prefetch_related`, otherwise this technique will not work for relation fields.

## Temporarily Turning Off the Optimizer

You can temporarily turn off the optimizer using the `disabled()` context manager:

```python
from strawberry_django.optimizer import DjangoOptimizerExtension

def my_resolver(info):
    # Optimizer is turned off within this block
    with DjangoOptimizerExtension.disabled():
        # Manual optimization or custom logic here
        return MyModel.objects.select_related("relation").all()
```

This is useful when you need complete control over the queryset optimization.

## Troubleshooting

### Extra queries still occurring

1. **Check that the extension is enabled**: Ensure `DjangoOptimizerExtension` is in your schema's extensions list
2. **Verify field names match**: The optimizer uses field names to determine what to optimize. Ensure your GraphQL field names match the model field names or use optimization hints
3. **Check for custom resolvers**: Custom resolvers bypass automatic optimization. Use optimization hints (`only`, `select_related`, `prefetch_related`) on the field

### "Deferred field" errors

If you see errors about accessing deferred fields, it usually means a property or method needs fields that weren't selected:

```python
# Problem: total needs price and quantity, but they might not be selected
@property
def total(self):
    return self.price * self.quantity

# Solution: Use optimization hints
@strawberry_django.field(only=["price", "quantity"])
def total(self) -> Decimal:
    return self.price * self.quantity
```

### Prefetch not working for nested relations

For nested relations with filters, ordering, or pagination, ensure `enable_nested_relations_prefetch=True` (the default).

If using custom connections, note that this optimization only works automatically with `ListConnection` and `DjangoListConnection`.

### Polymorphic queries not working

1. **With InheritanceManager**: Set `prefetch_custom_queryset=True` in the extension
2. **With Django Polymorphic**: Should work out of the box
3. **Custom solution**: Implement `resolve_type` and `get_queryset` on your interface type

### Performance still slow

1. Use Django Debug Toolbar to inspect actual queries being made
2. Check if the optimizer is being bypassed by custom resolvers
3. Consider using `@strawberry_django.field(annotate=...)` for computed fields to move computation to the database

## See Also

- [Fields](./fields.md) - Field-level optimization hints
- [Pagination](./pagination.md) - Pagination with optimization
- [Relay](./relay.md) - Relay connections with optimization