LearningNoob
LearningNoob

Reputation: 700

how to return a list of dictionary in graphene?

I am new on graphql and working with some datasets that is returned as a list of dictionaries.

snippet code:

class Player(ObjectType):
    username = String()
    role = String()

class Game(ObjectType):
    players = List(Player)

I'm wondering why below code doesn't work?

class Query(ObjectType):
        game_info = Field(Game, username=String(), role=String())
        
        def resolve_game_info(self, info):
            results =  [{
                        "username":"Malphite",
                        "role":"tank"
                        },
                        {
                        "username":"Teemo",
                        "role":"support"
                      }]
            output = []
            for res in results:
                 output.append(
                    Player(
                      username=res['username'],
                      role=res['role']
                    )
                  )

            return output

How I query in graphql:

query {
  game_info(username:"Teemo") {
    players {
      username
      role
    }
  }
}

Results to like this:

{
  "data": {
    "gameInfo": null
  }
}

Any help would this would be greatly appreciated!

Upvotes: 1

Views: 2164

Answers (1)

Sagar Adhikari
Sagar Adhikari

Reputation: 1382

The problem seems in format of returned data. Suppose, you have more fields in your Game, not only players. There is no way of including those fields in your return format.

Instead of return output .

Try: return {'players':output}

Upvotes: 2

Related Questions