如何在Django中使用GraphQL进行突变查询?

ffdz8vbo  于 2022-11-26  发布在  Go
关注(0)|答案(1)|浏览(146)
# 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'."

我遗漏了什么?正确的语法/表达式是什么?

jchrr9hc

jchrr9hc1#

为了防止对任何人有帮助,我修改了这个让它工作。

class Mutation(ObjectType):
    create_customer = graphene.Field(CreateCustomerMutation)

我变了,

create_customer = graphene.Field(CreateCustomerMutation)

create_customer = CreateCustomerMutation.Field()

相关问题