我正在尝试一个带有形式的graphene-django示例。但我收到下一个错误:
`graphql.error.base.GraphQLError:无法为不可为空的字段[MyMutationPayload.name]返回null。
我尝试在perform_mutate函数中的返回表达式中设置值。如果请求未执行所有变体,则无法使用。
class MyForm(forms.Form):
name = forms.CharField(min_length=10)
age = forms.IntegerField(min_value=0)
birth_date = forms.DateField()
class MyMutation(DjangoFormMutation):
class Meta:
form_class = MyForm
@classmethod
def perform_mutate(cls, form, info):
print('ok')
return cls(errors=[], name=form.cleaned_data.get('name'), age=form.cleaned_data.get('age'), birth_date=form.cleaned_data.get('birth_date'))
class Mutations():
my_mutation = MyMutation.Field()
class Mutation(Mutations, ObjectType):
pass
ROOT_SCHEMA = Schema(mutation=Mutation)
查询
mutation customMutation($data: MyMutationInput!){
myMutation(input: $data){
name
age
birthDate
errors{
field
messages
}
clientMutationId
}
}
变量
{
"data": {
"name": "Cristhiam",
"age": "-29",
"birthDate": "1990-04-06"
}
}
响应
{
"errors": [
{
"message": "Cannot return null for non-nullable field MyMutationPayload.name.",
"locations": [
{
"line": 3,
"column": 5
}
],
"path": [
"myMutation",
"name"
]
}
],
"data": {
"myMutation": null
}
}
突变结果应显示所有错误或所有表单值。
答案 0 :(得分:1)
按以下步骤更改代码
class MyForm(forms.Form):
name = forms.CharField(min_length=10)
age = forms.IntegerField(min_value=0)
birth_date = forms.DateField()
class MyMutation(DjangoFormMutation):
class Meta:
form_class = MyForm
@classmethod
def mutate_and_get_payload(cls, root, info, **input):
print('ok')
return cls(errors=[], name=input.get('name'), age=input.get('age'), birth_date=input.get('birth_date'))
class Mutations(ObjectType):
my_mutation = MyMutation.Field()
class Mutation(Mutations, ObjectType):
pass
ROOT_SCHEMA = Schema(mutation=Mutation)
输入是根据其文档传递给突变的参数。
答案 1 :(得分:1)
有效:
@classmethod
def perform_mutate(cls, form, info):
super().perform_mutate(form, info)
return cls(errors=[], **form.cleaned_data)