0

如何为 DRF 序列化程序创建 graphql 输入类型?

我正在使用 django rest 框架 (DRF) 序列化程序graphene-django,并且我能够看到在中CreateThingMutationInput定义的类型graphiql

  mutation TestCreate($input: CreateThingMutationInput!) {
    createProjectThing(input: $input) {
      id
      errors {
        field
        messages
      }
    }
  }

但是,我无法运行:

        schema = graphene.Schema(query=Query)
        result = schema.execute(self.query, variables=variables)

我得到:

[GraphQLError('Unknown type "CreateThingMutationInput".',)] 

具有以下内容:

class CreateThingMutation(SerializerMutation):
    class Meta:
        serializer_class = ThingListViewSerializer


class Mutation(graphene.ObjectType):
    debug = graphene.Field(DjangoDebug, name="_debug")

    create_project_thing = CreateThingMutation.Field()

我也试过:

class CreateThingMutationInput(graphene.ObjectType):
    input = graphene.Field(convert_serializer_to_input_type(ThingListViewSerializer))

以及尝试定义一个:

class Input:
    input = graphene.Field(convert_serializer_to_input_type(ThingListViewSerializer))

我还可以看到从graphql-codegenin定义的类型types.d.ts

export type CreateThingMutationInput = {
  id?: Maybe<Scalars['Int']>,
  ...
}

有关的:

4

1 回答 1

1

我忘了将mutationkwarg 添加到:

schema = graphene.Schema(query=Query)

应该:

schema = graphene.Schema(query=Query, mutation=Mutation)

发生这种情况的另一个原因GraphQLError('Unknown type "Number".',)是,如果查询函数收到意外参数,例如getThing使用 aNumber而不是a 调用ID

query TestQueryWontWork(id: Number="") {
   getThing(id: $id)
}

query TestQueryWorks(id: ID!) {
   getThing(id: $id)
}
于 2019-09-25T20:01:11.993 回答