【问题标题】:SQLAlchemy using wildcards or ILIKE for update statmentsSQLAlchemy 使用通配符或 LIKE 进行更新语句
【发布时间】:2023-04-04 10:02:01
【问题描述】:

我需要在更新语句中使用ilike,但是当我尝试时它返回此错误:

InvalidRequestError:无法评估 Python 中的当前标准。为 synchronize_session 参数指定 'fetch' 或 False。

对于此代码:

meta.Session.query(i.mappedClass).filter(getattr(i.mappedClass, j).ilike("%"+userid+"%")).update({j:newUserId})

我可以使用 regexp_replace 之类的东西,但这有点矫枉过正。我只想更新以适应不区分大小写和两端的空格。

【问题讨论】:

    标签: regex sqlalchemy sql-like


    【解决方案1】:

    试试这个:

    # test columns
    userid = "dUmMy"
    j = "name" # name of the column
    mappedTable = i.mappedClass.__table__ # assuming use of Declarative. if not, mappedTable is the Table object mapped to i.mappedClass
    _stmt = (mappedTable.update().where(getattr(i.mappedClass, j).ilike("%"+ userid +"%")).
                values({getattr(i.mappedClass, j): func.lower(getattr(i.mappedClass, j))})
            )
    session.execute(_stmt)
    

    产生 SQL:

    UPDATE person SET name=lower(person.name) WHERE lower(person.name) LIKE lower(?)
    

    实际上,您只需删除where 子句即可更新表中的所有记录:

    _stmt = mappedTable.update().values({getattr(i.mappedClass, j): func.lower(getattr(i.mappedClass, j))})
    session.execute(_stmt)
    

    产生这样的 SQL:

    UPDATE person SET name=lower(person.name)
    

    【讨论】:

    • 理想情况下,我想远离 session.execute,但我会对你在这里给出的东西搞砸,看看我能得到什么
    • 我看不出session.execute()query(...).update() 到底有什么不同?
    • 因为查询处于循环中,可能会导致打开多个连接出现问题
    • ...那么使用session.execute(...) 或者?
    【解决方案2】:

    好吧,这很令人沮丧!

    我发现的简单解决方法是这样的:

    for i in model.dataTables:
    for j in i.idColumn:
        rows = meta.Session.query(i.mappedClass).filter(getattr(i.mappedClass, j).ilike("%"+userid+"%")).all()
         for row in rows:
             setattr(row, j, newuserid)
    meta.Session.commit()
    

    【讨论】:

    • 这不仅仅是一种解决方法,而是一种不同的方法。您的第一种方法基本上是直接在 SQL 后端执行 SQL UPDATE 语句,而解决方法是将每一行作为模型对象加载到内存中,在内存中更新它,然后将更改提交到 SQL 后端。如果这是一种维护类型的操作,我认为第一种方法仍然会更好,特别是如果newuserid 可以从 SQL 后端的userid 计算出来。
    • 我不想在每个循环上都执行语句。第二种方式对我来说效果更好,因为用户不能在更新过程中中断循环。
    猜你喜欢
    • 2018-05-24
    • 1970-01-01
    • 1970-01-01
    • 2012-01-05
    • 2014-06-22
    • 2019-09-18
    • 2017-10-26
    相关资源
    最近更新 更多