我正在尝试为“复杂”对象实现 GrapgQL 突变。假设我们有一个Contact
包含三个字段的 a :和firstName
,它是一个包含一个字段的对象:lastName
address
street
这是我的python方案实现:
class Address(graphene.ObjectType):
street = graphene.String(description='Street Name')
class AddressInput(graphene.InputObjectType):
street = graphene.String(description='Street Name', required=True)
class Contact(graphene.ObjectType):
first_name = graphene.String(description='First Name')
last_name = graphene.String(description='Last Name')
address = graphene.Field(Address, description='Contact address')
class ContactInput(graphene.InputObjectType):
first_name = graphene.String(description='First Name', required=True)
last_name = graphene.String(description='Last Name', required=True)
address = AddressInput(description='Contact address', required=True)
class CreateContact(graphene.Mutation):
class Input:
contact = ContactInput()
contact = graphene.Field(Contact, description='Created Contact object')
@staticmethod
def mutate(instance, args, context, info):
contact = Contact(**args['contact'])
return CreateContact(contact=contact)
当我运行这个查询时:
mutation CreateContact($contact: ContactInput!) {
createContact(contact: $contact) {
contact {
firstName
address {
street
}
}
}
}
具有以下变量:
{
"contact": {
"address": {
"street": "Bond Blvd"
},
"firstName": "John",
"lastName": "Doe"
}
}
我得到以下结果:
{
"createContact": {
"contact": {
"address": {
"street": null
},
"firstName": "John"
}
}
}
如您所见,street
字段null
在结果中。
mutate
如果我改变方法,我可以得到我需要的东西:
@staticmethod
def mutate(instance, args, context, info):
args['contact']['address'] = Address(**args['contact']['address'])
contact = Contact(**args['contact'])
return CreateContact(contact=contact)
但我不确定这是正确的方法。
所以请建议一个正确的方法来启动嵌套结构。