在GraphQL更新中,我希望能够传递子对象的值,但我希望每个值都是可选的。
所以我创建了一个像这样的输入类:
class CityCouncilInput(graphene.InputObjectType):
mayor = graphene.String()
treasurer = graphene.String()
现在,我希望能够传递市长和掌柜的价值,或只传递其中一个。
请知道,如果传入了所有值,我的代码就可以正常运行。我只想让这些字段值可选。我该怎么做?
罗伯特
答案 0 :(得分:3)
你可以尝试
class CityCouncilInput(graphene.InputObjectType):
mayor = graphene.String(required=False, default=None)
treasurer = graphene.String(required=False, default=None)
答案 1 :(得分:1)
我认为最简单的方法是为变异函数定义默认参数
假设您使用以下模型,则您的值可以为空白(注意:我假设mayor
和treasurer
都可以为空白,但不允许{{ 1}}-否则我想您可以将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
答案 2 :(得分:0)
您可能只需要在mutate函数中运行if语句即可具有更新任何一个字段的能力,并且类updateCityCouncil的代码如下(PS:请注意名为CityCouncil和GraphQL的模型的假设型号)
class CityCouncilType(DjangoObjectType):
class Meta:
model = CityCouncil
class CityCouncilInput(graphene.InputObjectType):
id = graphene.Int()
mayor = graphene.String()
treasurer = graphene.String()
class updateCityCouncil(graphene.Mutation):
class Arguments:
id = graphene.Int(required=True)
input = CityCouncilInput(required=True)
ok = graphene.Boolean()
council = graphene.Field(CityCouncilType)
@staticmethod
def mutate(root, info, id, input=None):
ok = False
this_council = CityCouncil.objects.get(pk=id)
if this_council:
ok = True
if input.mayor is not None:
this_council.mayor = input.mayor
if input.treasurer is not None:
this_council.treasurer = input.treasurer
this_council.save()
return updateCityCouncil(ok=ok, council=this_council)
return updateCityCouncil(ok=ok, council=None)