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
|
---
title: Resolvers
---
# Custom Resolvers
Basic resolvers are generated automatically once the types are declared.
However it is possible to override them with custom resolvers.
## Sync resolvers
Sync resolvers can be used in both ASGI/WSGI and will be automatically wrapped
in `sync_to_async` when running async.
```python title="types.py"
import strawberry_django
from strawberry import auto
from . import models
@strawberry_django.type(models.Color)
class Color:
id: auto
name: auto
@strawberry_django.field
def fruits(self) -> list[Fruit]:
return self.fruits.objects.filter(...)
```
## Async resolvers
Async resolvers can be used when running using ASGI.
```python title="types.py"
import strawberry_django
from strawberry import auto
from . import models
from asgiref.sync import sync_to_async
@strawberry_django.type(models.Color)
class Color:
id: auto
name: auto
@strawberry_django.field
async def fruits(self) -> list[Fruit]:
return sync_to_async(list)(self.fruits.objects.filter(...))
```
## Optimizing resolvers
When using custom resolvers together with the [Query Optimizer Extension](optimizer.md)
you might need to give it a "hint" on how to optimize that field
Take a look at the [optimization hints](optimizer.md#optimization-hints)
docs for more information about this topic.
## Issues with Resolvers
It is important to note that overriding resolvers also removes default capabilities
(e.g. `Pagination`, `Filter`), exception for [relay connections](relay.md). You can
however still add those by hand and resolve them:
```python title="types.py"
import strawberry
from strawberry import auto
from strawberry.types import Info
import strawberry_django
from . import models
@strawberry_django.filter(models.Fruit, lookups=True)
class FruitFilter:
id: auto
name: auto
@strawberry_django.type(models.Fruit, order=FruitOrder)
class Fruit:
id: auto
name: auto
@strawberry_django.type(models.Fruit, is_interface=True)
class Fruit:
id: auto
name: auto
@strawberry.type
class Query:
@strawberry_django.field
def fruits(
self,
info: Info
filters: FruitFilter | None = strawberry.UNSET,
order: FruitOrder | None = strawberry.UNSET
) -> list[Fruit]:
qs = models.fruit.objects.all()
# apply filters if defined
if filters is not strawberry.UNSET:
qs = strawberry_django.filters.apply(filters, qs, info)
# apply ordering if defined
if order is not strawberry.UNSET:
qs = strawberry_django.ordering.apply(filters, qs)
return qs
```
|