突变 - 批量创建对象

时间:2017-05-19 12:44:01

标签: graphql graphene-python

我想用石墨烯一次创造出许多人。 该文件仅提到了创建这样一个人的方法:

class CreatePerson(graphene.Mutation):
class Input:
    name = graphene.String()
    age = graphene.Int()

ok = graphene.Boolean()
person = graphene.Field(lambda: Person)

@staticmethod
def mutate(root, args, context, info):
    person = Person(name=args.get('name'), age=args.get('age'), mobile=args.get('mobile'))
    ok = True
    return CreatePerson(person=person, ok=ok)

有没有办法让它完成?

4 个答案:

答案 0 :(得分:4)

您还可以调用在一个GraphQL请求中多次创建一个对象的突变,而不是使用创建对象列表的突变。这是使用GraphQL Aliases

完成的
mutation {
  c001: createPerson(
    name: "Donald Duck"
    age: 42
  ) {
    id
  }

  c002: createPerson(
    name: "Daisy Duck"
    age: 43
  ) {
    id
  }

  c003: createPerson(
    name: "Mickey Mouse"
    age: 44
  ) {
    id
  }
}

答案 1 :(得分:2)

将您的变异输入列表并返回已创建人员的列表。像这样:

class CreatePerson(graphene.Mutation):
    class Input:
        name = graphene.List(graphene.String)

    ok = graphene.Boolean()
    people = graphene.List(Person)

    @staticmethod
    def mutate(root, args, context, info):
        people = [Person(name=name) for name in args.get('name)]
        ok = True
        return CreatePerson(people=people, ok=ok)

答案 2 :(得分:1)

我可以根据Jan Hančič

的答案找出解决方案

在这种情况下,有一种名为graphene.InputObjectType的类型

解决方案可以是

class PersonInput(InputObjectType):
    name = graphene.String()
    age = graphene.Int()

class CreatePeople(graphene.Mutation):
    class Input:
       people = graphene.List(PersonInput)

    people = graphene.List(lambda: Person)

    @staticmethod
    def mutate(root, args, context, info):
        people = [Person.objects.create(name=person.name, age=person.age) for person in args.get('people')]
        return CreatePeople(people=people)

答案 3 :(得分:0)

接收输入列表,创建所有实例并全部返回

模型节点/类型应该像 -

class UserType(DjangoObjectType):

    class Meta:
        model = User
        interfaces = (CustomGrapheneNode, )
        filter_fields = {}
        only_fields = (
            'name',
            'email'
        )

定义输入字段

class UserInput(graphene.InputObjectType):
    name = graphene.String(required=True)
    password = graphene.String(required=True)

突变类

class CreateUser(graphene.Mutation):
    users = graphene.List(UserType)

    class Input:
        data = graphene.List(UserInput)

    Output = graphene.List(UserType)

    def mutate(self, info, data):
        users = []
        for item in data:
            user = User.objects.create(name=data['name'], 
                                       password=data['password'])
            users.append(user)
        return users

使这个变异可以被主模式

调用
class Mutation():
    create_user = CreateUser.Field()

Mutation Query视图将为 -

mutation{
    createUser(data:[{name:"john", password:"1234"},
                     {name:"john", password:"1234"}]) {
        user{
            name
        }
    }    
}