如何使Graphene输入类变量可选?

问题描述 投票:2回答:2

在GraphQL更新中,我希望能够传递子对象的值,但我希望每个值都是可选的。

所以我创建了一个这样的输入类:

class CityCouncilInput(graphene.InputObjectType):
  mayor = graphene.String()
  treasurer = graphene.String()

现在,我希望能够传递市长和财务主管的价值,或只传递其中一个。

如果所有值都被传入,请知道我的代码工作正常。我只想让这些字段值是可选的。我怎么做?

罗伯特

graphene-python
2个回答
3
投票

你可以试试

class CityCouncilInput(graphene.InputObjectType):
  mayor = graphene.String(required=False, default=None)
  treasurer = graphene.String(required=False, default=None)

1
投票

我认为最简单的方法是为变异函数定义一个默认参数

假设您有以下模型,其中您的值可以为空(注意:我假设mayortreasurer都将被允许为空白而不是NULL - 否则我猜您可以将None作为默认参数传递):

class CityCouncil(models.Model):
    mayor = models.TextField(max_length=1000, blank=True)
    treasurer = models.CharField(max_length=1000, blank=True)

然后创建市议会这应该工作:

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
        )

同样,在执行更新变异时,您可以传入可选参数,并使用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
        )
© www.soinside.com 2019 - 2024. All rights reserved.