graphene graphql dictionary as a type

烈酒焚心 提交于 2019-12-08 16:41:38

问题


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


回答1:


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. If you want to define a dictionary, it has to be be explicit. This means '12345' and '76788' should have keys defined for them. 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
        }
      }
    ]
  }
}


来源:https://stackoverflow.com/questions/46402182/graphene-graphql-dictionary-as-a-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!