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

Peewee组合同表多组OR子句为AND条件查询结果为空问题排查

问题根因

  • 你仅对StockGroupTicker表做了一次关联,生成的SQL中对应别名t3,最终WHERE条件要求同一条t3记录的stock_index_id同时匹配indices和brokers两个维度的取值,该逻辑不可能成立,因此查询结果为空。
  • 现有代码中brokers维度的筛选也错误复用了StockGroupTicker.stock_index字段,两个维度的筛选逻辑完全混淆。

修复方案

你需要对StockGroupTicker表分别做两次独立关联,分别对应indices和brokers两个维度的筛选,代码修改如下:

from peewee import JOIN

...
# 第一次关联专门用于indices筛选
StockGroupTickerIndex = StockGroupTicker.alias('group_index')
query = query.join(StockGroupTickerIndex, JOIN.INNER, on=(Ticker.id == StockGroupTickerIndex.ticker))
# indices筛选逻辑
if "indices" in filter:
    where_indices = []
    for f in filter["indices"]:
        where_indices.append(StockGroupTickerIndex.stock_index == int(f))
    if len(where_indices):
        query = query.where(peewee.reduce(peewee.operator.or_, where_indices))

# 第二次关联专门用于brokers筛选
StockGroupTickerBroker = StockGroupTicker.alias('group_broker')
query = query.join(StockGroupTickerBroker, JOIN.INNER, on=(Ticker.id == StockGroupTickerBroker.ticker))
# brokers筛选逻辑
if "brokers" in filter:
    where_broker = []
    for f in filter["brokers"]:
        # 注意:如果broker对应的字段不是stock_index,请替换为实际字段名
        where_broker.append(StockGroupTickerBroker.stock_index == int(f))
    if len(where_broker):
        query = query.where(peewee.reduce(peewee.operator.or_, where_broker))

return query.distinct()

逻辑说明

修改后生成的SQL会对stockgroupticker表关联两次、使用不同别名,indices维度的条件加在第一次关联的表上,brokers维度的条件加在第二次关联的表上,即可正确筛选出同时满足两个维度条件的记录。

内容的提问来源于stack exchange,提问作者g.breeze

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 03:36:06