Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/335.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 作为一种类型的graphene graphql字典_Python_Graphql_Graphene Python - Fatal编程技术网

Python 作为一种类型的graphene graphql字典

Python 作为一种类型的graphene graphql字典,python,graphql,graphene-python,Python,Graphql,Graphene Python,我是一个石墨烯的新手,我试图将下面的结构映射到一个对象类型,但没有成功 { "details": { "12345": { "txt1": "9", "txt2": "0" }, "76788": { "txt1": "6", "txt2": "7" } } } 非常感谢您的指导 谢谢不清楚您试图实现什么,但是(据我所知),在定义GraphQL模式时,您不应该有任何任意的键/值名称。如果要定义字典,

我是一个石墨烯的新手,我试图将下面的结构映射到一个对象类型,但没有成功

    {
  "details": {
    "12345": {
      "txt1": "9",
      "txt2": "0"
    },
    "76788": {
      "txt1": "6",
      "txt2": "7"
    }
  }
}
非常感谢您的指导

谢谢

不清楚您试图实现什么,但是(据我所知),在定义GraphQL模式时,您不应该有任何任意的键/值名称。如果要定义字典,它必须是显式的。这意味着“12345”和“76788”应该为它们定义键。例如:

类自定义字典(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
如果我们对此提出疑问:

我们得到:


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


Ref:

关于您遇到的问题的更多信息以及出现这些问题的代码示例将非常有用。我们在这里真的没什么可谈的,伙计。使用GenericScalar完成这项工作
query {
  details {
    key
    value {
      txt1
      txt2
    }
  }
}
{
  "data": {
    "details": [
      {
        "key": 76788,
        "value": {
          "txt1": 6,
          "txt2": 7
        }
      },
      {
        "key": 12345,
        "value": {
          "txt1": 9,
          "txt2": 0
        }
      }
    ]
  }
}