如何在 postgresql 数组字段上使用 ilike sqlalchemy?

编程入门 行业动态 更新时间:2024-10-25 10:25:28
本文介绍了如何在 postgresql 数组字段上使用 ilike sqlalchemy?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试使用以下代码将一些名称与我在 Postgresql 数据库中已有的名称相匹配:

I'm trying to match some names with the names I already have in my Postgresql database, using the following code:

last_like = '{last_name}%'.format(last_name) matches = Session.query(MyTable).filter(or_( MyTable.name.ilike(last_like), MyTable.other_names.any(last_like, operator=ilike_op), )).all()

本质上,它尝试匹配 name 列 或 以数组形式存储在 other_names 列中的任何其他名称.

Essentially it tries to match the name column or any of the other names stored as an array in the other_names column.

但我明白了:

KeyError: <function ilike_op at 0x7fb5269e2500>

我做错了什么?

推荐答案

要使用 postgresql 数组字段,您需要使用 unnest() 函数.但是你不能在 where 子句中使用 unnest() 的结果.

For use postgresql array field you need to use unnest() function. But you can't use result of unnest() in where clause.

相反,您可以使用 array_to_string 函数.搜索 other_names 的字符串将产生相同的效果

Instead, you can use array_to_string function. Searching on string of other_names will give the same effect

from sqlalchemy import func as F last_like = "%qq%" matches = session.query(MyTable).filter(or_( MyTable.name.ilike(last_like), F.array_to_string(MyTable.other_names, ',').ilike(last_like), )).all()

更多推荐

如何在 postgresql 数组字段上使用 ilike sqlalchemy?

本文发布于:2023-10-16 16:52:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1498167.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   字段   如何在   sqlalchemy   postgresql

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!