2016-05-30 91 views
1

我有一個數據庫,並試圖使用MID()函數查詢信息。在正常的SQL我會用MID如(從W3例如網站)..Python SQLALCHEMY查詢使用MID()

SELECT MID(City,1,4) AS ShortCity 
FROM Customers; 

轉換這SQLAlchemy的已經有點挑戰性。我能夠使用分頁執行查詢,但不能使用中間值。到目前爲止,我有 的作品原始查詢..

links = Item.query.filter(Item.title.like('%' +search_term +'%')).paginate(page, 10, True) 

將其轉換成不工作..

links = Item.query.filter(func.mid(Item.title.like, 1, 3)('%' +search_term + '%')).paginate(page, 10, True) 



    TypeError: 'Function' object is not callable 

我想從題目中的字符的XY量(字符串列)

+0

我可以看到你缺少逗號''',即'func.mid(Item.title.like,1,3)('%'+ search_term +'%')'應該是'func .mid(Item.title.like,1,3),('%'+ search_term +'%')'。看看是否解決了這個問題,這段代碼可能有其他的錯誤,但是遇到typeerror是因爲從func.mid(...)返回的對象不可調用,並且'('%'+ search_term +'%') '然後被視爲函數參數 –

+0

給出了diff錯誤.. – Anekdotin

+0

OperationalError:(sqlite3.OperationalError)在「%」附近:語法錯誤[SQL:u'SELECT items.id AS items_id,items.title AS items_title,items.link AS items_link,items.description AS items_description,items.member_since AS items_member_since,items.last_updated AS items_last_updated,items.click_count AS items_click_count \ nFROM items \ nWHERE mid(?,?,?)AND%tor%\ n LIMIT? OFFSET?'] [參數:(<綁定方法InstrumentedAttribute.like,如>,1,3,10,0)] – Anekdotin

回答

1

我可以看到你在

之間缺少一個逗號 ,
func.mid(Item.title.like, 1, 3)('%' +search_term + '%') 

它使括號中的第二個表達式成爲第一個參數。這是例外

TypeError: 'Function' object is not callable. 

的來源,但,以產生LIKE操作,嘗試:

func.mid(Item.title, 1, 3).like('%' +search_term + '%') 

這給了你,你的Python代碼似乎暗示WHERE子句。 在您的代碼中,like錯位。

但是,如果你想生成的SQL語句:

SELECT MID(City,1,4) AS ShortCity 
FROM Customers; 

適當SQLAlchemy的代碼將

session.query(func.mid(Customer.city, 1, 4).label('ShortCity')) 

假設模型被稱爲Customer並有一個名爲city場。

+0

即時通訊,但爲什麼session.query通過Item.query?我的項目設置錯了嗎? – Anekdotin

+0

不,它們都是有效的,我只是_happened_明確地使用會話編寫我的查詢。幕後,sqlalchemy仍在創建一個會議。 –

+0

無法讓它工作.. :( – Anekdotin