[英]graphene graphql dictionary as a type
I'm a newbie for the graphene and I'm trying to map the following structure into a Object Type and having no success at all我是石墨烯的新手,我正在尝试将以下结构映射到对象类型中,但根本没有成功
{
"details": {
"12345": {
"txt1": "9",
"txt2": "0"
},
"76788": {
"txt1": "6",
"txt2": "7"
}
}
}
Any guidance is highly appreciated任何指导都受到高度赞赏
Thanks谢谢
It is unclear what you are trying to accomplish, but (as far as I know) you should not have any arbitrary key/value names when defining a GraphQL schema.目前还不清楚您想要完成什么,但是(据我所知)在定义 GraphQL 模式时您不应该有任何任意的键/值名称。 If you want to define a dictionary, it has to be be explicit.
如果你想定义一个字典,它必须是明确的。 This means '12345' and '76788' should have keys defined for them.
这意味着 '12345' 和 '76788' 应该为它们定义密钥。 For instance:
例如:
class CustomDictionary(graphene.ObjectType):
key = graphene.String()
value = graphene.String()
Now, to accomplish a schema similar to what you ask for, you would first need to define the appropriate classes with:现在,要完成类似于您所要求的架构,您首先需要使用以下内容定义适当的类:
# 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)
Now we need a way to resolve the dictionary into these objects.现在我们需要一种方法将字典解析为这些对象。 Using your dictionary, here's an example of how to do it:
使用您的字典,以下是如何操作的示例:
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
If we query this with:如果我们查询这个:
query {
details {
key
value {
txt1
txt2
}
}
}
We get:我们得到:
{
"data": {
"details": [
{
"key": 76788,
"value": {
"txt1": 6,
"txt2": 7
}
},
{
"key": 12345,
"value": {
"txt1": 9,
"txt2": 0
}
}
]
}
}
You now can use graphene.types.generic.GenericScalar
您现在可以使用
graphene.types.generic.GenericScalar
Ref : https://github.com/graphql-python/graphene/issues/384参考: https : //github.com/graphql-python/graphene/issues/384
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.