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
相关产品推荐
相关产品推荐

