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

前端 未结 1 1031
长情又很酷
长情又很酷 2021-01-13 23:48

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 follow

1条回答
  •  隐瞒了意图╮
    2021-01-14 00:05

    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}

    Other Input Types

    This approach could easily be extended for other input types beyond integers, for example replacing

        int_value = graphene.Int(...
    

    with

        str_value = graphene.String(...
    

    0 讨论(0)
提交回复
热议问题