【发布时间】:2020-07-25 20:05:00
【问题描述】:
这是我的简单场景。我有一个模型,其中包含两个必填字段名称和年龄:
class Person(models.Model):
name = models.CharField(max_length=256)
age = models.PositiveIntegerField()
我正在使用带有 Graphene 的 Django 模型表单
class PersonForm(forms.ModelForm):
class Meta:
model = Person
fields = ('name', 'age')
class PersonType(DjangoObjectType):
class Meta:
model = Person
class PersonMutation(DjangoModelFormMutation):
class Meta:
form_class = PersonForm
class Mutation(graphene.ObjectType):
person_mutation = PersonMutation.Field()
假设一个人填写了年龄字段但没有填写姓名字段。然后我可以发送一个变异查询
mutation {
personMutation(input: {age: 25, name: ""}) {
errors {
field
messages
}
}
}
我得到以下响应,这正是我想要的。此响应很容易通过,我会收到名称字段验证消息。
{
"data": {
"personMutation": {
"errors": [
{
"field": "name",
"messages": [
"This field is required."
]
}
]
}
}
}
但是如果用户填写姓名而不填写年龄怎么办?我应该做什么样的突变查询?
如果我做
mutation {
personMutation(input: {name: "my name"}) {
errors {
field
messages
}
}
}
我收到以下回复。这是一个可怕的消息,我无法向用户展示。响应 json 格式也与以前不同。
{
"errors": [
{
"message": "Argument \"input\" has invalid value {name: \"my name\"}.\nIn field \"age\": Expected \"Int!\", found null.",
"locations": [
{
"line": 2,
"column": 25
}
]
}
]
}
如果我尝试将age: null 或age: "" 作为输入参数,那就更好了。那么在未设置年龄的情况下,如何获取 Django 的“此字段为必填项”验证消息?
【问题讨论】:
-
当你只插入年龄而根本没有名字,甚至没有一个空字符串时,你会得到什么响应?
-
只给出年龄会给出相同的不需要的错误消息:参数输入无效......所以问题也存在,但您可以通过给出一个空字符串作为参数来解决它。但是对于其他类型是不可能的