You need to enable JavaScript to run this app. 如何修改GraphQL的info对象SelectionSet以正确获取目标FieldNode?
优惠活动
大模型
产品
解决方案
定价
更多

如何修改GraphQL的info对象SelectionSet以正确获取目标FieldNode?

问题解决方法

你当前拿到的info.field_nodes[0]是顶层查询字段(即allLibrary)对应的AST节点,它的选择集只包含allLibrary下直接请求的results、__typename字段,目标字段name、book是嵌套在results字段的选择集内的,按以下步骤调整即可获取:

  • 从顶层字段的选择集中筛选出results对应的FieldNode
  • 访问results节点的selection_set.selections属性,即可得到目标字段的FieldNode列表

代码示例

from graphql import FieldNode

# 取顶层allLibrary字段的所有子选择
top_selections = info.field_nodes[0].selection_set.selections

# 筛选results字段的FieldNode
results_node = next(
    sel for sel in top_selections
    if isinstance(sel, FieldNode) and sel.name.value == "results"
)

# 非空判断避免查询未指定results子字段时报错
if results_node.selection_set:
    target_selections = results_node.selection_set.selections
    # 此处target_selections就包含你需要的name、book等FieldNode

如果存在多层嵌套的查询场景,可以通过递归遍历每个FieldNode的selection_set的方式,提取任意层级的请求字段。

内容的提问来源于stack exchange,提问作者Lukasz Dynowski

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.12 18:03:03