The below method updates single emp record , how to handle the same for multiple emp recs at the same time.
{
(id : 1, firstName : "John", lastName: "Snow"),
(id : 2, firstName : "Tryrion", lastName: "Lannister")
(id : 3, firstName : "Jammie", lastName: "Lannister")
}
I am new to django and graphql kindly help me with code and query for the same
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
}
}
}
CodePudding user response:
To update multiple objects you need to define a new type and accordingly update your code like this:
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)
query:
mutation{
uopdatemp(input_type: [{id: 1, firstName: "John", lastName: "Snow"}, {id: 2, firstName: "Tryrion", lastName: "Lannister"}])
{
Employee{
id
firstName,
lastName
}
}
}