首页 > 解决方案 > 界面中包含的 Graphql 类型未添加到 graphene-django 中的模式

问题描述

我有一个由两种具体类型实现的接口类型

interface InterfaceType {
  id: ID!
  name: String!
}

 type Type1 implements InterfaceType {
    aField: String
}

 type Type2 implements InterfaceType {
    anotherField: String
}

使用石墨烯-django:

class InterfaceType(graphene.Interface):
    id = graphene.ID(required=True)
    name = graphene.String(required=True)

class Type1(graphene_django.types.DjangoObjectType):
    a_field = graphene.String(required=False)

    class Meta:
        model = Model1
        interfaces = (InterfaceType,)

class Type2(graphene_django.types.DjangoObjectType):
    another_field = graphene.String(required=False)

    class Meta:
        model = Model2
        interfaces = (InterfaceType,)

只要某些查询或突变直接使用Type1和,这就会起作用Type2。但在我的情况下,它们只是通过InterfaceType.

问题是当我尝试请求aFieldanotherField通过内联片段时:

query {
    interfaceQuery {
        id
        name
        ...on Type1 {
            aField
        }
        ...on Type2 {
            anotherField
        }
    }

使用反应阿波罗:

import gql from 'graphql-tag';

const interfaceQuery = gql`
    query {
        interfaceQuery {
            id
            name
            ... on Type1 {
                aField
            }
            ... on Type2 {
                anotherField
            }
        }
    }
`;

我得到错误"Unknown type "Type1". Perhaps you meant ..."

这就像类型没有添加到架构中,因为它们没有直接使用 - 但我仍然需要它们才能查询aFieldanotherField.

你能发现上面的错误吗?

标签: interfacegraphqlreact-apollographene-pythongraphene-django

解决方案


尝试显式地将Type1和添加Type2到您的架构中。石墨烯需要你的一点点指导才能知道你想将这些类型添加到你的模式中。

schema = graphene.Schema(
    query=Query,
    mutation=Mutation,
    types=[
        Type1,
        Type2,
    ]
)

文档中也提到了这一点(尽管我猜有点容易忽略)。当您查看示例代码时,有这样一行:

schema = graphene.Schema(query=Query, types=[Human, Droid])

因此,这(顺便说一句)可能是一个很好的例子,说明为什么即使您可以写行长,最好不要将某些内容折叠成一行。


推荐阅读