You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Graphene Python中实现带参数的嵌套多对多查询?

解决Graphene Python中多对多关系的嵌套参数查询问题

问题原因

你遇到的Unknown argument 'customerId' on field 'Components.linkedParts'错误,本质是**Components.linked_parts字段没有定义对应的参数**,Graphene无法识别传入的customerId参数。要实现带参数的嵌套查询,需要给目标字段添加参数定义,并编写对应的解析逻辑。

解决方案步骤

1. 给linked_parts字段添加参数定义

修改Components类的linked_parts字段,显式声明支持的参数(如customer_id、limit、offset),Graphene会自动将Python风格的下划线参数转换为GraphQL的驼峰命名(比如customer_id对应查询中的customerId)。

注意:你的Products和Components类必须继承graphene.ObjectType,否则Graphene无法识别为GraphQL对象类型。

import graphene

class Products(graphene.ObjectType):
    id = graphene.Int()
    name = graphene.String()
    customer_id = graphene.Int()
    linked_components = graphene.List(graphene.NonNull(lambda: Components))

class Components(graphene.ObjectType):
    id = graphene.Int()
    name = graphene.String()
    # 给linked_parts字段添加参数支持
    linked_parts = graphene.List(
        graphene.NonNull(lambda: Products),
        customer_id=graphene.Int(),  # 对应查询中的customerId
        limit=graphene.Int(),
        offset=graphene.Int()
    )

2. 编写linked_parts的解析函数

在Components类中添加resolve_linked_parts方法,实现根据当前组件实例、传入参数筛选关联产品的逻辑。这里需要结合你的数据库多对多关联方式(比如中间表)来编写查询:

class Components(graphene.ObjectType):
    id = graphene.Int()
    name = graphene.String()
    linked_parts = graphene.List(
        graphene.NonNull(lambda: Products),
        customer_id=graphene.Int(),
        limit=graphene.Int(),
        offset=graphene.Int()
    )

    def resolve_linked_parts(self, info, customer_id=None, limit=None, offset=None):
        # 当前组件的ID
        current_component_id = self.id
        
        # 第一步:获取当前组件关联的所有产品ID(根据你的多对多中间表实现)
        # 示例:从中间表查询关联的product_id列表
        linked_product_ids = info.context["env"]["component_product"].search(
            [('component_id', '=', current_component_id)],
            fields=['product_id']
        )
        # 提取ID值(根据你的ORM返回格式调整)
        product_id_list = [item['product_id'] for item in linked_product_ids]
        
        # 第二步:添加customer_id筛选条件
        domain = [('id', 'in', product_id_list)]
        if customer_id:
            domain.append(('customer_id', '=', customer_id))
        
        # 第三步:查询并返回符合条件的产品
        return info.context["env"]["product"].search(
            domain,
            limit=limit,
            offset=offset
        )

3. 验证查询

修改完成后,你期望的GraphQL查询即可正常执行:

query myquery {
  allProducts(customerId: 8) {
    id
    name
    linkedComponents {
      id
      name
      linkedParts(customerId:8) {
        id
        name
      }
    }
  }
}

补充说明

  • 如果Products.linked_components也需要支持参数查询,可以用同样的方式添加参数和解析函数。
  • 解析函数中的多对多关联查询逻辑需要根据你实际的数据库结构(比如Odoo模型关联)调整,确保能正确获取关联的产品ID。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 21:36:33