【问题标题】:How to write this in SQL Alchemy如何在 SQL Alchemy 中编写此代码
【发布时间】:2014-02-28 05:41:31
【问题描述】:

我需要在 SQL Alchemy 中编写一个查询来针对包含字符串数组 (Postgre) 的字段检查一些字符串参数

城市 状态 地址第一行 邮政编码 电话号码

都是 text[] 类型

    select_statement = bdb.get_select_statement(business_schema)\
    .where(((text('array[:acity] <@ city')
            and text('array[:astate] <@ state')
            and text('array[:aaddress] <@ address_line_1'))
    or
           (text('array[:aaddress] <@ address_line_1') and text('array[:azip_code] <@ zip_code')))
    and  (text('array[:aphone] <@ phone_numbers')))\
    .params(aaddress = address_line_1, acity = city, astate = state, azip_code = zip_code, aphone = phone_number)

问题是我在执行此操作时收到异常,“未定义此子句的布尔值”。

要写的纯SQL是:

select * from business where ('address_line1' = ANY (address_line_1) 
                              and 'acity' = ANY (city) 
                              and 'state' = ANY (state)
or
        ('adress_line1' = ANY (address_line_1) and 'zip' = ANY (zip_code))
and
'phone' = ANY (phone_numbers)

关于如何做的任何想法?,

提前致谢!

【问题讨论】:

    标签: sqlalchemy


    【解决方案1】:

    您需要使用and_()or_() 方法,或者&amp;&amp;|| 运算符,而不是Python 的andor 关键字。

    此外,您使用数组索引和“

    mytable.c.array[:"acity"].op('<@')(mytable.c.city)
    

    ARRAY

    【讨论】:

      【解决方案2】:

      使用 SqlAlchemy 0.8,这可以写成:

      mytable.c.myarraycolumn.contains(['something'])

      或者,使用声明类:

      query.filter(MyTable.myarraycolumn.contains(['something']))

      http://docs.sqlalchemy.org/en/latest/dialects/postgresql.html#sqlalchemy.dialects.postgresql.ARRAY

      【讨论】:

        【解决方案3】:

        这是我们在 SQLAlchemy 0.9 中实现此功能的方法。

        SQLAlchemy 不知道如何在这些查询中将 Python 类型转换为数组元素类型。由于我们的数组元素是VARCHAR(256) 而不是TEXT,我们必须在array 文字中添加一个cast 表达式。

        session.query.filter(
            models.TableClass.arraycolumn.contains(   
                # contains() generates @>, and @> always takes an array, 
                # it's more like has-subset
                array([
                    # the array() literal constructor needs an iterable
                    cast(
                        'array-element-to-find', 
                        # SQLAlchemy does not know how to convert a Python string 
                        # to an SQL VARCHAR type here
                        String(256),
                    )
                ])
            )
        ).all()
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-05-03
          • 1970-01-01
          • 1970-01-01
          • 2017-08-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多