繁体   English   中英

如何使用 graphene-django 为突变定义自定义输出类型?

[英]How can I define custom output types for mutations with graphene-django?

创建/删除/更新/删除(CRUD)突变通常返回相应的数据库模型实例作为突变的输出类型。 但是,对于非 CRUD 突变,我想定义特定于业务逻辑的突变输出类型。 例如,返回列表元素的计数 + 不能在 graphql 类型和 db 模型之间进行 1 对 1 映射的 ID 列表。 我怎样才能用graphene-django实现这一点?

与模型无关的列表

由于您想同时返回计数和元素列表,您可以创建自定义类型:

class ListWithCountType(graphene.Scalar):

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

然后在您的突变中,您可以像这样使用它:

class MyMutation(graphene.Mutation):
    list_with_count = graphene.Field(ListWithCountType)

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

添加到您的架构:

class Query(graphene.ObjectType):
    my_mutation = MyMutation.Field()

应该返回如下内容:

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

*PS:如果这只是一个输出,好的。 但是如果你想让这个类型成为一个参数,除了“序列化”之外,你还应该实现“parse_literal”和“parse_value”。

是一个与表单一起使用的自定义 ErrorType 的示例。

模型相关列表

文档

# cookbook/ingredients/schema.py

import graphene

from graphene_django.types import DjangoObjectType

from cookbook.ingredients.models import Category


class CategoryType(DjangoObjectType):
    class Meta:
        model = Category

class Query(object):
    all_categories = graphene.List(CategoryType)

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

在您的架构上:

import graphene

import cookbook.ingredients.schema


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

schema = graphene.Schema(query=Query)

然后你可以查询:

query {
  allCategories {
    id
  }
}

应该返回如下内容:

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

这是一个带有用户模型示例

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM