Skip to content Skip to sidebar Skip to footer

How Can I Define Custom Output Types For Mutations With Graphene-django?

Create/remove/update/delete (CRUD) mutations usually return the corresponding database model instance as output type of the mutation. However for non-CRUD mutations I'd like to def

Solution 1:

List not related to Models

As you want to return both a count and a list of elements, you can create a custom type:

classListWithCountType(graphene.Scalar):

    @staticmethoddefserialize(some_argument):
        # make computation here
        count = ...
        some_list = ...
        return { "count": count, "list": some_list }

Then on your mutation you use it like this:

classMyMutation(graphene.Mutation):
    list_with_count = graphene.Field(ListWithCountType)

    @classmethoddefmutate(cls, root, info, **kwargs):
        some_argument = kwargs.pop("some_argument")
        return cls(list_with_count=some_argument)

Add to your schema:

classQuery(graphene.ObjectType):
    my_mutation = MyMutation.Field()

Should return something like:

{
  "data": {
    "list_with_count": {
      "count": <COUNT VALUE>,
      "list": <SOME_LIST VALUE>
    }
  }
}

*PS: if this is only an output, ok. But if you want this type to be an argument, you should also implement "parse_literal" and "parse_value", besides the "serialize".

Here is an example with a custom ErrorType used with forms.

List related to Models

From the docs:

# cookbook/ingredients/schema.pyimport graphene

from graphene_django.types import DjangoObjectType

from cookbook.ingredients.models import Category


classCategoryType(DjangoObjectType):
    classMeta:
        model = Category

classQuery(object):
    all_categories = graphene.List(CategoryType)

    defresolve_all_categories(self, info, **kwargs):
        return Category.objects.all()

On your schema:

import graphene

import cookbook.ingredients.schema


classQuery(cookbook.ingredients.schema.Query, graphene.ObjectType):
    pass

schema = graphene.Schema(query=Query)

Then you can query like:

query {
  allCategories {
    id
  }
}

Should return something like:

{"data":{"allCategories":[{"id":"1",},{"id":"2",},{"id":"3",},{"id":"4",}]}}

Here is an example with user model.

Post a Comment for "How Can I Define Custom Output Types For Mutations With Graphene-django?"