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
)
default_value
for recent versions ofgraphene
– Apodictic