如何在 graphql django 更新突变中处理多个记录

how to handle multiple records in graphql django update mutation

下面的方法更新单个emp记录,如何同时处理多个emp记录。

{
(id : 1, firstName : "John", lastName: "Snow"),
(id : 2, firstName : "Tryrion", lastName: "Lannister")
(id : 3, firstName : "Jammie", lastName: "Lannister")
}

我是 django 的新手,graphql 请帮助我编写代码并查询相同的内容

class UpdateEmp(graphene.Mutation):
    emp = graphene.Field(EmployeeType)

class Arguments:
    id = graphene.Int(required=True)
    first_name = graphene.String()
    last_name = graphene.String()

@login_required
def mutate(self, info,**kwargs):
    emp = Employee.objects.get(id=kwargs.get('id'))
    emp.first_name=kwargs.get('first_name')
    emp.last_name=kwargs.get('last_name')
    emp.save()
    return UpdateEmp(emp=emp)

graphql

mutation{
  uopdatemp(id : 1, firstName : "john", lastName: "Snow")
  {
    Employee{
      id
      firstName,
      lastName
    }
    
  }

}
  

要更新多个对象,您需要定义一个新类型并相应地更新您的代码,如下所示:

types.py

class InputType(graphene.ObjectType):
    id = graphene.Int(required=True)
    first_name = graphene.String()
    last_name = graphene.String() 

mutation.py

class UpdateEmp(graphene.Mutation):
    emps = graphene.List(EmployeeType)

class Arguments:
    input_type = graphene.List(InputType)

@login_required
def mutate(self, info, objs):
    emp_list = [Employee.objects.filter(id=obj.pop('id')).update(**obj) for obj in objs]
    return UpdateEmp(emps=emp_list)

查询:

mutation{
  uopdatemp(input_type: [{id: 1, firstName: "John", lastName: "Snow"}, {id: 2, firstName: "Tryrion", lastName: "Lannister"}])
  {
    Employee{
      id
      firstName,
      lastName
    }
    
  }

}