Defining Types¶
Output types¶
Note
It is highly recommended to enable the Query Optimizer Extension for improved performance and avoid some common pitfalls (e.g. the n+1 issue)
Output types are generated from models. The auto type is used for field type auto resolution. Relational fields are described by referencing to other types generated from Django models. A many-to-many relation is described with the typing.List type annotation. strawberry_django will automatically generate resolvers for relational fields. More information about that can be read from resolvers page.
| types.py | |
|---|---|
Input types¶
Input types can be generated from Django models using the strawberry_django.input decorator. The first parameter is the model which the type is derived from.
| types.py | |
|---|---|
A partial input type, in which all auto-typed fields are optional, is generated by setting the partial keyword argument in input to True. Partial input types can be generated from existing input types through class inheritance.
Non-auto type annotations will be respected—and therefore required—unless explicitly marked Optional[].
Types from Django models¶
Django models can be converted to strawberry Types with the strawberry_django.type decorator. Custom descriptions can be added using the description keyword argument (See: strawberry.type decorator API).
| types.py | |
|---|---|
Adding fields to the type¶
By default, no fields are implemented on the new type. Check the documentation on How to define Fields for that.
Customizing the returned QuerySet¶
Warning
By doing this you are modifying all automatic QuerySet generation for any field that returns this type. Ideally you will want to define your own resolver instead, which gives you more control over it.
By default, a strawberry_django type will get data from the default manager for its Django Model. You can implement a custom get_queryset classmethod to your type to do some extra processing to the default queryset, like filtering it further.
| types.py | |
|---|---|
The get_queryset classmethod is given a QuerySet to filter and a strawberry Info object containing details about the request.
You can use that info parameter to, for example, limit access to results based on the current user in the request:
Note
Another way of limiting this is by using the PermissionExtension provided by this lib.
The kwargs dictionary can include other parameters that were added in a @strawberry.django.type definition like filters or pagination.