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

如何在GraphQL Schema中处理where子句?Flask-GraphQL实践问题

解决GraphQL where子句及类型错误的方案

1. 修复「Unknown type 'Long'」错误

GraphQL标准类型中没有Long,月份属于整数范畴,直接改用Int类型即可。修改后的查询语句:

query dataClosingSoon($month: Int) {
  query{
    data(where: { LastModifiedDate: { CALENDAR_MONTH: { value: { eq: $month } } } } ) {
      edges { ....... }
    }
  }
}

2. 修复「Unknown argument 'where' on field 'QueryCustom.data'」错误

你的Schema中QueryCustom.data字段未定义where参数,需要先定义对应的嵌套输入类型,再给字段添加该参数:

修改后的Schema片段

# 定义数值相等条件输入类型
input NumericEqualityInput {
  eq: Int
}

# 定义月份筛选条件输入类型
input CalendarMonthInput {
  value: NumericEqualityInput
}

# 定义日期过滤条件输入类型
input DateFilterInput {
  CALENDAR_MONTH: CalendarMonthInput
}

# 定义data字段的where参数输入类型
input DataWhereInput {
  LastModifiedDate: DateFilterInput
}

type data {
    edges:[data_edges]
}

type QueryCustom {
    # 给data字段添加where参数
    data(where: DataWhereInput): data
}

type Query {
    query: QueryCustom
}

在Resolver中实现过滤逻辑

以Flask常用的Graphene框架为例,需要在QueryCustom的Resolver函数中解析where参数,完成数据过滤:

from graphene import ObjectType, Field, InputObjectType, Int, String, List

# 对应Schema中的输入类型
class NumericEqualityInput(InputObjectType):
    eq = Int()

class CalendarMonthInput(InputObjectType):
    value = Field(NumericEqualityInput)

class DateFilterInput(InputObjectType):
    CALENDAR_MONTH = Field(CalendarMonthInput)

class DataWhereInput(InputObjectType):
    LastModifiedDate = Field(DateFilterInput)

# 定义data_edges的具体字段
class DataEdges(ObjectType):
    id = Int()
    name = String()
    last_modified = String()

class Data(ObjectType):
    edges = Field(List(DataEdges))

class QueryCustom(ObjectType):
    data = Field(Data, where=DataWhereInput())

    def resolve_data(self, info, where=None):
        # 模拟数据库原始数据
        raw_data = [
            {"id": 1, "name": "商品A", "last_modified": "2024-05-12"},
            {"id": 2, "name": "商品B", "last_modified": "2024-06-20"},
            {"id": 3, "name": "商品C", "last_modified": "2024-06-25"},
        ]

        # 根据where条件过滤数据
        if where and where.LastModifiedDate and where.LastModifiedDate.CALENDAR_MONTH:
            target_month = where.LastModifiedDate.CALENDAR_MONTH.value.eq
            filtered_data = [
                item for item in raw_data
                if int(item["last_modified"].split("-")[1]) == target_month
            ]
        else:
            filtered_data = raw_data

        # 转换为GraphQL要求的返回格式
        edges = [DataEdges(**item) for item in filtered_data]
        return Data(edges=edges)

class Query(ObjectType):
    query = Field(QueryCustom)

核心说明

  • GraphQL中接收复杂参数必须使用输入类型(InputObjectType),需要逐层定义嵌套的条件结构,才能让where参数合法。
  • Resolver是业务逻辑的核心,需要解析where中的条件规则,对数据源进行过滤后返回符合格式的数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 22:31:59