在Django中如何正确执行GraphQL的Mutation查询?
问题:Django GraphQL Mutation参数错误排查与修复
问题描述
在Django中定义了Customer模型、CustomerNode及CreateCustomerMutation等GraphQL相关代码后,尝试两种Mutation查询均报错:
- Query1提示参数'name'和'address'不存在
- Query2提示参数'input'不存在
相关代码
# Model class Customer(models.Model): name = models.CharField(max_length=150) address = models.CharField(max_length=150) # Node class CustomerNode(DjangoObjectType): class Meta: model = Customer interfaces = (relay.Node,) # Mutations class CreateCustomerMutation(relay.ClientIDMutation): class Input: name = graphene.String(required=True) address = graphene.String() customer = graphene.Field(CustomerNode) @classmethod def mutate_and_get_payload(cls, root, info, **input): customer_instance = Customer( name=input["name"], address=input["address"], ) customer_instance.save() return CreateCustomerMutation(customer=customer_instance) class Mutation(ObjectType): create_customer = graphene.Field(CreateCustomerMutation) # Schema schema = graphene.Schema(query=Query, mutation=Mutation)
尝试的查询
# Query 1 mutation { createCustomer(name: "John", address: "Some address") { id, name } } # Query 2 mutation { createCustomer(input: {name: "John", address: "Some address"}) { id, name } }
报错信息
# Query 1 "Unknown argument 'name' on field 'Mutation.createCustomer'." "Unknown argument 'address' on field 'Mutation.createCustomer'." # Query 2 "Unknown argument 'input' on field 'Mutation.createCustomer'."
错误原因
问题出在Mutation的注册方式:使用relay.ClientIDMutation时,不能直接用graphene.Field()声明字段,必须调用CreateCustomerMutation.Field()方法。ClientIDMutation内部会自动处理input参数的结构,直接用graphene.Field()无法生成正确的字段定义,导致GraphQL无法识别传入的参数。
修复步骤
修改Mutation类中create_customer字段的定义:
class Mutation(ObjectType): # 替换原来的 graphene.Field(CreateCustomerMutation) create_customer = CreateCustomerMutation.Field()
正确的查询语法
修复后,必须使用input参数包裹所有字段,同时注意返回结构需要先获取customer字段,再访问其属性:
mutation { createCustomer(input: {name: "John", address: "Some address"}) { customer { id, name, address } } }
说明:relay.ClientIDMutation的返回值是包含你定义的customer字段的对象,因此不能直接在createCustomer下取id、name,必须嵌套一层customer。
内容的提问来源于stack exchange,提问作者HappyChappy
相关产品推荐
相关产品推荐

