Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make Graphene Input Class variables optional?

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

like image 293
Robert_LY Avatar asked Aug 24 '17 22:08

Robert_LY


2 Answers

You can try

class CityCouncilInput(graphene.InputObjectType):
  mayor = graphene.String(required=False, default=None)
  treasurer = graphene.String(required=False, default=None)
like image 175
Jason Marsh Avatar answered Sep 17 '22 17:09

Jason Marsh


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
        )
like image 25
Hendrik F Avatar answered Sep 17 '22 17:09

Hendrik F