2016-11-22 34 views
1

在我的postgresql數據庫中有一個表,其中有一個整數數據類型的列。我想用peewee python orm執行一個.contains操作。使用包含在python peewee和postgresql的整數列中

它似乎不起作用,因爲在比較發生之前需要將整數值轉換爲字符串。在postgresql中,您可以執行value :: text,然後整數值將是一個字符串,您可以在類似的表達式中使用它。

我可以使用peewee orm來做這件事,先將值轉換,然後使用.contains?或者,也許有另一種方式?

例如,我想匹配20出2022022

感謝

回答

1

我看到一對夫婦的答案,但我只添加自己的0.02作爲庫的開發。

from playhouse.shortcuts import cast 

query.where(cast(Url.http_status_code, 'text').contains(search_val)) 

我不知道這是更好的性能(可能TO_CHAR),但以防萬一你要找的東西更通用的,你可以使用cast

0
def python_partial_match(needle,key,haystack): 
    for item in haystack.select(): 
     if needle in str(getattr(item,key,None)): 
      yield item 

for result in python_partial_match("20","phone_number",UserModelClass): 
    print "GOT RESULT:",result 

,但它的將是大數據集,我認爲

或者我認爲你可以做的很慢像

PostgresqlDatabase.register_ops({'::', '::'}) 

@Node.extend() 
def cast(self, as_type): 
    return Expression(self, '::', SQL(as_type)) 

DataModel.select().where(DataModel.integer_col.cast('str').contains("20")) 

也許...我沒有測試,鑄造thi NG ......(見http://docs.peewee-orm.com/en/latest/peewee/api.html?highlight=cast#Node.extend

實際上它看起來像有在劇場一個內置cast Postgres的看到http://docs.peewee-orm.com/en/latest/peewee/playhouse.html?highlight=cast#cast

+0

不幸的是,這些建議並沒有爲我工作,但我確實找到了一種方法 – user964491