2012-12-21 84 views
3

我需要寫在SQL鍊金術查詢查一些字符串參數對包含字符串數組(Postgre)如何在SQL鍊金術寫這

城市 狀態 地址行 ZIP_CODE PHONE_NUMBERS

都是文本類型的[]

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) 

關於如何做到這一點的任何想法?

謝謝!

回答

4

您需要使用and_()or_()方法,或者在&&||運營商,而不是Python的andor關鍵字。

此外,你用數組索引做的操作和 「< @」 是更容易做到(0.8)是這樣的:

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

看到ARRAY

+0

感謝yoou zzzeek,這正是我一直在尋找! –

2

下面是我們如何得到這個在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()