QyzForest 2025-09-06 15:12 采纳率: 0%
浏览 5

graphene-django 跑mutation报意外实参

首先我直接复制了官方的代码,就是这段

import graphene

from graphene_django import DjangoObjectType

from .models import 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 Mutation(graphene.ObjectType):
    update_question = QuestionMutation.Field()


然后在这一部分return QuestionMutation(question=question)里面的question=question报意外实参。有人知道是为什么吗?

我是运行在pycharm上,然后python版本3.13,graphene-django 3.2.3
官网代码的地址:https://docs.graphene-python.org/projects/django/en/latest/mutations/

  • 写回答

5条回答 默认 最新

  • 码农阿豪@新空间 新星创作者: 前端开发技术领域 2025-09-06 15:12
    关注
    让阿豪来帮你解答,本回答参考chatgpt3.5编写提供,如果还有疑问可以评论或留言
    根据你的描述,你在使用Graphene-Django进行mutation时遇到了一个报错,报错信息显示在return语句中的"question=question"中有意外实参。这个问题可能是由于你在QuestionMutation类的构造函数中传入了一个错误的参数导致的。 在官方的代码中,返回QuestionMutation时确实有一个构造函数的调用,但是这个构造函数应该接受的参数是一个dictionary,而不是直接的"question=question"。 为了解决这个问题,你可以修改QuestionMutation类的构造函数,使其接受一个包含"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 Mutation(graphene.ObjectType):
        update_question = QuestionMutation.Field()
    

    在这个修改后的代码中,我们将构造函数的调用改为传入一个dictionary,其中键是"question",值是我们获取的question对象。 希术这个修改能够解决你遇到的问题。如果还有其他问题或需要进一步的帮助,请随时告诉我。

    评论

报告相同问题?

问题事件

  • 创建了问题 9月6日