【发布时间】:2021-03-07 01:12:14
【问题描述】:
虽然我已经能够使我的应用程序正常工作,但我还是担心以正确的方式做事。因此,有些东西我“不明白”:
在文档here 中,QuestionMutation 类中有一个question 属性。这实际上是什么意思?它说它定义了响应,我不明白这是什么意思。
文档中的代码:
class QuestionType(DjangoObjectType):
class Meta:
model = Question
class QuestionMutation(graphene.Mutation):
class Arguments:
# The input arguments for this mutation
text = graphene.String(required=True)
id = graphene.ID()
# The class attributes define the response of the mutation
question = graphene.Field(QuestionType)
@classmethod
def mutate(cls, root, info, text, id):
question = Question.objects.get(pk=id)
question.text = text
question.save()
# Notice we return an instance of this mutation
return QuestionMutation(question=question)
在我的代码中,我已经能够做到这一点:
我的类型:
class UserType(DjangoObjectType):
class Meta:
model = User
fields = (
'id',
'username',
'password',
'email',
'first_name',
'last_name',
'is_active',
'group_ids',
)
full_name = graphene.String() # Python property
full_identification = graphene.String() # Python property
我的突变:
class UpdateUser(graphene.Mutation):
# --------> I could comment these and no problem. Why ? <--------
# id = graphene.ID()
# username = graphene.String()
# email = graphene.String()
# first_name = graphene.String()
# last_name = graphene.String()
# is_active = graphene.Boolean()
class Arguments:
id = graphene.ID()
username = graphene.String()
email = graphene.String()
first_name = graphene.String()
last_name = graphene.String()
is_active = graphene.Boolean()
class Meta:
output = UserType
@login_required
def mutate(self, info, **kwargs):
user = get_object_or_404(User, id=kwargs['id'])
for attr, value in kwargs.items():
setattr(user, attr, value)
user.save()
return user
# I'm not returning explicit UserType, is it a problem ?
# I actually do it with the Meta class. I guess it is the same for this ?
它可以工作,而我没有为响应属性指定任何内容。我什至不返回同样的东西。 如果我做错了,有人可以解释一下吗?
你可以在这里看到,如果我称之为突变:
mutation {
updateUser (
id: 42
username: "updated_user"
firstName: "updated"
lastName: "user"
email: "updated.user@test.com"
) {
id
username
firstName
lastName
email
}
}
即使没有返回值,我也能得到这个答案:
{
"data": {
"updateUser": {
"id": "42",
"username": "updated_user",
"firstName": "updated",
"lastName": "user",
"email": "updated.user@test.com"
}
}
}
【问题讨论】:
标签: django graphene-python graphene-django