如何使用 Graphene GraphQL 解析嵌套在另一种类型中的字段?

jpe*_*nna 8 python graphql graphene-python

我有 3 个文件:authors.py,posts.pyschema.py.

帖子有一个作者,查询构建在架构文件中。

我试图Author从内部Post解析而不在 中声明解析器函数Post,因为Author已经声明了一个解析器函数。以下代码有效,但我必须resolve_authorPost类型内部进行引用,这似乎不对。我认为 Graphene 应该parent直接将参数传递给Author,不是吗?

如果我没有authorPost类型中设置解析器,它只会返回null.

模式.py

import graphene
from graphql_api import posts, authors


class Query(posts.Query, authors.Query):
    pass


schema = graphene.Schema(query=Query)
Run Code Online (Sandbox Code Playgroud)

作者.py

from graphene import ObjectType, String, Field


class Author(ObjectType):
    id = ID()
    name = String()


class Query(ObjectType):
    author = Field(Author)

    def resolve_author(parent, info):
        return {
            'id': '123',
            'name': 'Grizzly Bear',
            'avatar': '#984321'
        }

Run Code Online (Sandbox Code Playgroud)

帖子.py

from graphene import ObjectType, String, Field
from graphql_api import authors


class Post(ObjectType):
    content = String()
    author = Field(authors.Author)

    def resolve_author(parent, info):
        # I'm doing like this and it works, but it seems wrong. 
        # I think Graphene should be able to use my resolver 
        # from the Author automatically...
        return authors.Query.resolve_author(parent,
                                            info, id=parent['authorId'])


class Query(ObjectType):
    post = Field(Post)

    def resolve_post(parent, info):
        return {
            'content': 'A title',
            'authorId': '123',
        }
Run Code Online (Sandbox Code Playgroud)

don*_*yyy 2

Query.resolve_author不会被调用,因为它和对象之间没有关系Post

我建议类似:

from graphene import ObjectType, String, Field
from graphql_api import authors


class Post(ObjectType):
    content = String()
    author = Field(authors.Author)

    def resolve_author(self, info):
        # author_utils.get_author returns complete object that will be passed into Author's object resolvers (if some fields are missing)
        # I suggest returning here an object from database so author resolver would extract another fields inside
        # But it may be just an id that will be passed in Author resolvers as first arguments
        return author_utils.get_author(post_id=self.id)


class Query(ObjectType):
    post = Field(Post)

    def resolve_post(parent, info):
        # Here you shouldn't author_id as it's not defined in type 
        return {
            'content': 'A title',
        }
Run Code Online (Sandbox Code Playgroud)

并且Author(假设author_utils.get_author只返回一个 id):

class Author(ObjectType):
    id = ID()
    name = String()

    def resolve_id(id, info):
        # root here is what resolve_author returned in post. Be careful, it also will be called if id is missing after Query.resolve_author
        return id

    def resolve_name(id, info):
        # same as resolve_id
        return utils.get_name_by_id(id)
Run Code Online (Sandbox Code Playgroud)