In a GraphQL update mutation I want to be able to pass in the values for a child object but I want each of those values to be optional.
So I have created an Input Class like this:
class CityCouncilInput(graphene.InputObjectType):
mayor = graphene.String()
treasurer = graphene.String()
Now, I want to be able to pass in either values for both the mayor and treasurer or just one of them.
Pleas know that my code works fine if ALL of the values are passed in. I just want those field values to be optional. How do I do that?
Robert
You can try
class CityCouncilInput(graphene.InputObjectType):
mayor = graphene.String(required=False, default=None)
treasurer = graphene.String(required=False, default=None)
I think the easiest is to define a default argument for the mutation function
Assuming you have the following model, where your values can be blank (Note: I assumed both mayor
and treasurer
would be allowed to be blank but not NULL
- otherwise I guess you can pass None
as a default argument):
class CityCouncil(models.Model):
mayor = models.TextField(max_length=1000, blank=True)
treasurer = models.CharField(max_length=1000, blank=True)
Then to create the city council this should work:
class createCityCouncil(graphene.Mutation):
mayor = graphene.String()
treasurer = graphene.String()
class Arguments:
mayor = graphene.String()
treasurer = graphene.String()
def mutate(self, mayor="", treasurer=""):
council = CityCouncil(mayor=mayor, treasurer=treasurer)
council.save()
return createCityCouncil(
mayor=council.mayor,
treasurer=council.treasurer
)
Similarly, when performing an update mutation, you can pass in optional arguments and selectively update the property on your object with setattr
).
class updateCityCouncil(graphene.Mutation):
mayor = graphene.String()
treasurer = graphene.String()
class Arguments:
mayor = graphene.String()
treasurer = graphene.String()
def mutate(self, info, id, **kwargs):
this_council=CityCouncil.objects.get(id=id)
if not this_council:
raise Exception('CityCouncil does not exist')
for prop in kwargs:
setattr(this_council, prop, kwargs[prop])
this_council.save
return updateCityCouncil(
mayor=this_council.mayor,
treasurer=this_council.treasurer
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With