【问题标题】:graphene graphql dictionary as a type石墨烯 graphql 字典作为一种类型
【发布时间】:2018-03-06 05:52:16
【问题描述】:

我是石墨烯的新手,我正在尝试将以下结构映射到 Object Type 并且根本没有成功

    {
  "details": {
    "12345": {
      "txt1": "9",
      "txt2": "0"
    },
    "76788": {
      "txt1": "6",
      "txt2": "7"
    }
  }
}

非常感谢任何指导
谢谢

【问题讨论】:

  • 有关您遇到的问题的更多信息以及出现这些问题的代码示例会有所帮助。伙计,我们真的没什么可谈的。
  • github.com/graphql-python/graphene/issues/… 使用 GenericScalar 完成这项工作

标签: python graphql graphene-python


【解决方案1】:

目前尚不清楚您要完成什么,但(据我所知)在定义 GraphQL 模式时,您不应该有任何任意键/值名称。如果你想定义一个字典,它必须是明确的。这意味着“12345”和“76788”应该为它们定义键。例如:

class CustomDictionary(graphene.ObjectType):
    key = graphene.String()
    value = graphene.String()

现在,要完成类似于您要求的架构,您首先需要定义适当的类:

# Our inner dictionary defined as an object
class InnerItem(graphene.ObjectType):
    txt1 = graphene.Int()
    txt2 = graphene.Int()

# Our outer dictionary as an object
class Dictionary(graphene.ObjectType):
    key = graphene.Int()
    value = graphene.Field(InnerItem)

现在我们需要一种方法来将字典解析为这些对象。使用你的字典,下面是一个例子:

class Query(graphene.ObjectType):

    details = graphene.List(Dictionary)  
    def resolve_details(self, info):
        example_dict = {
            "12345": {"txt1": "9", "txt2": "0"},
            "76788": {"txt1": "6", "txt2": "7"},
        }

        results = []        # Create a list of Dictionary objects to return

        # Now iterate through your dictionary to create objects for each item
        for key, value in example_dict.items():
            inner_item = InnerItem(value['txt1'], value['txt2'])
            dictionary = Dictionary(key, inner_item)
            results.append(dictionary)

        return results

如果我们这样查询:

query {
  details {
    key
    value {
      txt1
      txt2
    }
  }
}

我们得到:

{
  "data": {
    "details": [
      {
        "key": 76788,
        "value": {
          "txt1": 6,
          "txt2": 7
        }
      },
      {
        "key": 12345,
        "value": {
          "txt1": 9,
          "txt2": 0
        }
      }
    ]
  }
}

【讨论】:

    【解决方案2】:

    您现在可以使用graphene.types.generic.GenericScalar

    参考:https://github.com/graphql-python/graphene/issues/384

    【讨论】:

      猜你喜欢
      • 2017-05-11
      • 2017-05-13
      • 2020-05-03
      • 2018-03-11
      • 2020-07-27
      • 2018-03-22
      • 2020-03-23
      • 2020-09-19
      • 2020-02-25
      相关资源
      最近更新 更多