19

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

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

非常感谢任何指导
谢谢

4

2 回答 2

23

目前尚不清楚您要完成什么,但是(据我所知)在定义 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
        }
      }
    ]
  }
}
于 2018-07-24T01:08:42.677 回答
6

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

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

于 2020-06-23T14:18:39.653 回答