Mutations
Getting started
Mutations can be defined the same way as
strawberryβs mutations , but instead of
using @strawberry.mutation
, use @strawberry_django.mutation
.
Here are the differences between those:
- Strawberry Djangoβs mutation will be sure that the mutation is executed in an async safe
environment, meaning that if you are running ASGI and you define a
sync
resolver, it will automatically be wrapped in async_to_async
call. - It will better integrate with the permission integration
- It has an option to automatically handle common django errors and return them in a standardized way (more on that below)
Django errors handling
When defining a mutation you can pass handle_django_errors=True
to make it handle
common django errors, such as ValidationError
, PermissionDenied
and ObjectDoesNotExist
:
The code above would generate following schema:
Tip
If all or most of your mutations use this behaviour, you can change the
default behaviour for handle_django_errors
by setting
MUTATIONS_DEFAULT_HANDLE_ERRORS=True
in your strawberry django settings
Input mutations
Those are defined using @strawberry_django.input_mutation
and act the same way as
the @strawberry_django.mutation
, the only difference being that it injects
an InputMutationExtension
in the field, which converts its arguments in a new type (check the extensionβs docs
for more information).
CUD mutations
The following CUD mutations are provided by this lib:
-
strawberry_django.mutations.create
: Will create the model using the data from the given input -
strawberry_django.mutations.update
: Will update the model using the data from the given input -
strawberry_django.mutations.delete
: Will delete the model using the id from the given input
A basic example would be:
Some things to note here:
- Those CUD mutations accept the same arguments as
@strawberry_django.mutation
accepts. This allows you to passhandle_django_errors=True
to it for example. - The mutation will receive the type in an argument named
"data"
by default. To change it to"info"
for example, you can change it by passingargument_name="info"
to the mutation, or setMUTATIONS_DEFAULT_ARGUMENT_NAME="info"
in your strawberry django settings to make it the default when not provided. - Take note that inputs using
partial
will not automatically mark non-auto fields optional and instead will respect explicit type annotations; see partial input types documentation for examples. - Iβs also possible to update or delete model by using unique identifier other than id by providing
key_attr
property :
Filtering
Caution
This is totally discouraged as it allows for any issue with the filters to be able to alter your whole model collection.
Filters can be added to update and delete mutations. More information in the filtering section.