【问题标题】:How can I define custom output types for mutations with graphene-django?如何使用 graphene-django 定义突变的自定义输出类型?
【发布时间】:2020-05-19 23:34:56
【问题描述】:

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

【问题讨论】:

  • 您的意思是返回与某个模型相关的 ID 列表?还是一些随机列表?
  • @pedrobern 我的意思首先是与模型/ID 无关的输出。我已经调整了问题以使其更清楚。
  • 我已经编辑了我的答案,看看它现在是否有效

标签: python django graphql graphene-django graphql-mutation


【解决方案1】:

与模型无关的列表

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

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:如果这只是一个输出,好的。但是如果你想让这个类型成为一个参数,除了“serialize”之外,你还应该实现“parse_literal”和“parse_value”。

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

与模型相关的列表

来自docs

# 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",
      }
    ]
  }
}

这是example with user model

【讨论】:

    猜你喜欢
    • 2019-04-26
    • 2017-09-18
    • 1970-01-01
    • 1970-01-01
    • 2020-11-19
    • 2019-03-07
    • 2011-07-25
    • 2014-03-01
    • 2020-10-28
    相关资源
    最近更新 更多