Pass array of links in mutation [graphene/python/graphql]

Viewed 456

i'm a little bit confuses about using graphene. I am using the example of mutations on https://www.howtographql.com/graphql-python/3-mutations/ , but here only the example is shown how to create ONE link. Now it is more realistic for me that you have a list of links or other objects that you pass to your backend and later database. Is there anyone who has already implemented such an example?

1 Answers

I have taken a different example from https://docs.graphene-python.org/en/latest/types/mutations/#inputfields-and-inputobjecttypes . Below code snippet should help you in creating multiple instances in a single mutation.

import graphene
from .models import Person

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

class PersonType(DjangoObjectType):
    class Meta:
        model = Person

class CreatePerson(graphene.Mutation):
    class Arguments:
        person_objects = graphene.List(PersonInput, required=True)

    persons = graphene.List(PersonType)

    def mutate(root, info, person_objects):
        persons = list()
    
        for person_data in person_objects:
            person = Person.objects.create(
                name=person_data.name,
                age=person_data.age
            )
            persons.append(person)
    
        return CreatePerson(persons=persons)

mutation:

createPerson(personObjects: [{name: "Danish Wani" age:28}, {name: "Wani Danish" age:29}]){
    persons{
      name
      age
    }
  }
Related