gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 18:56:43 25 4
gpt4 key购买 nike

我有 3 个文件:authors.pyposts.pyschema.py

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

我正在尝试从 Post 中解析 Author 而无需在 Post 中声明解析器函数,因为 Author 已经为自己声明了一个解析器函数。以下代码有效,但我必须从 Post 类型中引用 resolve_author 并且它似乎不正确。我认为 Graphene 应该将 parent 参数直接传递给 Author,不是吗?

如果我没有在 Post 类型中为 author 设置解析器,它只会返回 null

schema.py

import graphene
from graphql_api import posts, authors


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


schema = graphene.Schema(query=Query)

作者.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'
}

posts.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',
}

最佳答案

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',
}

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)

关于python - 如何使用 Graphene GraphQL 解析嵌套在另一种类型中的字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57392186/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com