Search code examples
graphqlgraphene-python

Mutations - batch creation of objects


I want to use graphene to create many people in one go. The document only mention the way to create one person like this:

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)

are there any ways to get it done?


Solution

  • I can figure out a solution base on the answer of Jan Hančič

    There is a type called graphene.InputObjectType to use in this case

    The solution can be

    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)