我正在尝试为“复杂”对象实现GrapgQL变异。假设我们有一个Contact
,其中有三个字段: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)
但我不确定这是否正确。
因此,请建议正确的方法来启动嵌套结构。