石墨烯图形字典

2024-10-02 20:39:22 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

我们非常感谢任何指导
谢谢


Tags: 对象类型details结构指导石墨新手txt1
1条回答
网友
1楼 · 发布于 2024-10-02 20:39:22

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

class CustomDictionary(graphene.ObjectType):
    key = graphene.String()
    value = graphene.String()

现在,要完成与您所要求的类似的模式,首先需要使用以下内容定义适当的类:

^{pr2}$

现在我们需要一种将字典解析为这些对象的方法。下面是一个使用字典的示例:

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
        }
      }
    ]
  }
}

相关问题 更多 >