Django Graphene,将JSON或dict数据作为突变输入 [英] Django Graphene, Passing JSON or dict data as input for Mutation
问题描述
我有以下情况:我有一个用户,每个用户都有一个清单。我正在努力在Mutation CreateUser中声明用户的广告资源。以下是创建用户的以下突变:
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?
推荐答案
您可以创建一个自定义对象类型来表示一个键值对,然后在用户模式中列出这些对象。
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)
语法有点笨拙但可行:
mutation {addUser(name: Shibunika,年龄:21,广告资源:[{name: item1 ,intValue:45},{name: item2,intValue:25}]){ok}
其他输入类型
此方法可以轻松扩展到整数以外的其他输入类型,例如替换
This approach could easily be extended for other input types beyond integers, for example replacing
int_value = graphene.Int(...
with
str_value = graphene.String(...
这篇关于Django Graphene,将JSON或dict数据作为突变输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!