graphene graphql 字典作为一种类型

问题描述 投票:0回答:3

我是石墨烯的新手,我正在尝试将以下结构映射到对象类型,但完全没有成功

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

非常感谢任何指导
谢谢

python graphql graphene-python
3个回答
25
投票

目前尚不清楚您要实现什么目标,但(据我所知)在定义 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
        }
      }
    ]
  }
}

8
投票

您现在可以使用

graphene.types.generic.GenericScalar

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


0
投票

如果您确实有一个动态创建的字典,但您事先不知道确切的结构,则可以使用 GenericScalar 类型。 请参阅下面的示例:

import graphene
from graphene.types.generic import GenericScalar


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

class GenericDictType(graphene.ObjectType):
    generic_dict_field = GenericScalar()

class Query(graphene.ObjectType):
    generic_dict = graphene.Field(GenericDictType)

    def resolve_generic_dict(self, info):
        return GenericDictType(example_dict)

然后您就可以提出请求:

query {
  genericDict {
    genericDictField
  }
}

并得到以下回复:

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

但是,如果您的字典结构是固定的,那么最好使用 GraphQL 字段定义结构,如其他答案中所建议的。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.