我是石墨烯的新手,我正在尝试将以下结构映射到对象类型并且根本没有成功
{
"details": {
"12345": {
"txt1": "9",
"txt2": "0"
},
"76788": {
"txt1": "6",
"txt2": "7"
}
}
}
任何指导都非常感谢
谢谢
解决方法:
目前还不清楚你要完成什么,但是(据我所知)你在定义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
}
}
]
}
}