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

Python数据库搜索过滤问题:多条件精确匹配失效修复

问题分析与代码修正

原代码核心问题在于使用or_逻辑,导致只要任一条件匹配就返回结果,无法实现多条件组合的精确匹配;同时未处理空输入字段,会引入无效的匹配逻辑。以下是修正后的代码:

def search_results(search):
    results = []
    # 提取输入数据并去除首尾空白,处理空值
    lieu = search.data.get('Lieu', '').strip()
    annee = search.data.get('Annee', '').strip()
    signataire = search.data.get('Signataire', '').strip()
    cote = search.data.get('Cote', '').strip()
    sujet = search.data.get('Sujet', '').strip()
    categorie = search.data.get('Categorie', '').strip()

    # 初始化基础查询
    qry = db_session.query(Cote)
    filters = []

    # 逐个添加有效过滤条件
    if lieu:
        filters.append(Cote.lieu == lieu)
    if annee:
        filters.append(Cote.annee == annee)
    if cote:
        filters.append(Cote.cote == cote)
    if categorie:
        filters.append(Cote.categorie == categorie)
    if signataire:
        # 签名字段匹配:姓名或头衔任一符合即满足
        filters.append(or_(
            Cote.signataire_nom == signataire,
            Cote.signataire_titre == signataire
        ))
    if sujet:
        # 主题字段匹配:任一主题列符合即满足
        filters.append(or_(
            Cote.sujet_1 == sujet,
            Cote.sujet_2 == sujet,
            Cote.sujet_3 == sujet
        ))

    # 用and_组合所有条件,确保填写的条件全部满足
    if filters:
        qry = qry.filter(and_(*filters))
        results = qry.all()
    
    return results

关键修正说明

  • 逻辑组合优化:替换原有的or_为and_组合所有有效条件,保证只有满足所有填写条件的记录才会被返回
  • 空值过滤:仅当输入字段有实际内容时才添加对应过滤规则,避免空字符串干扰匹配结果
  • 多列字段处理:针对signataire和sujet这类对应多列的字段,内部用or_实现“任一列匹配”,再与其他条件用and_组合,符合业务需求
  • 精确匹配实现:将原代码的contains改为==,实现严格的精确匹配;若需要模糊匹配,可改回contains,但需保持多条件同时满足的逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 05:36:22