Django Graphene, Passing JSON or dict data as input for Mutation

人走茶凉 提交于 2019-12-08 01:37:04

问题


I have the following situation: I have a User, each user has a Inventory. I'm struggling to declare the user's inventory in the Mutation "CreateUser". Here is the following mutation for creating the user:

mutation Create{
  addUser(UserData:{name:"Shibunika",age:21}
}

I'm trying to declare the user's inventory in this mutation, I expected something like

mutation Create{
  addUser(UserData:{name:"Shibunika",age:21,inventory:{'item1':45,'item2':25}
}s

these number are the quantity of each item. How do I define these inputs in graphene? Would you gently show me a schema for this?


回答1:


You can create a custom object type to represent a key value pair, and then have a list of these in your user schema.

class InventoryKeyValueType(graphene.InputObjectType):
    name = graphene.String(required=True)
    int_value = graphene.Int(required=True)

class AddUser(graphene.Mutation):
    user = graphene.Field(lambda: UserType)
    ok = graphene.Boolean()

    class Arguments:
        # User Fields
        name = graphene.String()
        ....

        inventory = graphene.List(InventoryKeyValueType)

The syntax is a bit clunky but workable:

mutation { addUser(name:"Shibunika", age:21, inventory:[ {name: "item1", intValue: 45}, {name: "item2", intValue:25}]){ok}



来源:https://stackoverflow.com/questions/51224477/django-graphene-passing-json-or-dict-data-as-input-for-mutation

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