首页 > 解决方案 > 使用 array.contains() 对 postgresql 数组列进行查询过滤

问题描述

我有一个数组列(我需要,我知道这不是典型的约定),我需要在查询中对其进行过滤。我正在尝试使用 contains(),

  db.session.query(table).filter((table.name.ilike
    ('%'+name+'%')),
    table.languages.contains(language)).limit(200)

但我不断收到此错误:

    NotImplementedError: ARRAY.contains() not implemented for the base 
    ARRAY 
    type; please use the dialect-specific ARRAY type

我是 Flask-Sqlalchemy 的新手,所以我不确定如何正确使用它。任何帮助深表感谢!

标签: pythonpostgresqlflask-sqlalchemy

解决方案


这个期望意味着你应该使用dialect-specific ARRAY type来代替基本的 ARRAY 类型。所以在你的模型定义中,使用sqlalchemy.dialects.postgresql.ARRAYtoARRAY

from sqlalchemy.dialects.postgresql import ARRAY
class table(db.Model):
    ...
    languages = db.Column(ARRAY) # notice this ARRAY import from sqlalchemy.dialects.postgresql

现在,您可以使用db.session.query(table).filter(table.languages.contains([language])).limit(200).


推荐阅读