2017-05-08 152 views
-1

我試圖總結兩列中的值並截斷日期中的日期字段。我已經構造SQL查詢來做到這一點(工作):peewee select()返回SQL查詢,而不是實際數據

SELECT date_trunc('day', date) AS Day, SUM(fremont_bridge_nb) AS 
Sum_NB, SUM(fremont_bridge_sb) AS Sum_SB FROM bike_count GROUP BY Day 
ORDER BY Day; 

但我再遇到問題時,我嘗試這種格式爲peewee:

Bike_Count.select(fn.date_trunc('day', Bike_Count.date).alias('Day'), 
fn.SUM(Bike_Count.fremont_bridge_nb).alias('Sum_NB'), 
fn.SUM(Bike_Count.fremont_bridge_sb).alias('Sum_SB')) 
.group_by('Day').order_by('Day') 

我沒有得到任何錯誤,但是當我打印出來的變量我存儲在這,它表明:

<class 'models.Bike_Count'> SELECT date_trunc(%s, "t1"."date") AS 
Day, SUM("t1"."fremont_bridge_nb") AS Sum_NB, 
SUM("t1"."fremont_bridge_sb") AS Sum_SB FROM "bike_count" AS t1 ORDER 
BY %s ['day', 'Day'] 

,我已經用Python寫的順利拿到數據的唯一事情是:

Bike_Count.get(Bike_Count.id == 1).date 

回答

0

如果您只是通過/ order by將一個字符串粘貼到您的組中,Peewee會嘗試將其參數化爲一個值。這是爲了避免SQL注入haxx。

爲了解決這個問題,你可以代替'Day'group_by()order_by()電話內使用SQL('Day')

另一種方法是將函數調用插入GROUP BYORDER BY。這裏是你會怎麼做:

day = fn.date_trunc('day', Bike_Count.date) 
nb_sum = fn.SUM(Bike_Count.fremont_bridge_nb) 
sb_sum = fn.SUM(Bike_Count.fremont_bridge_sb) 

query = (Bike_Count 
     .select(day.alias('Day'), nb_sum.alias('Sum_NB'), sb_sum.alias('Sum_SB')) 
     .group_by(day) 
     .order_by(day)) 

或者,如果你喜歡:

query = (Bike_Count 
     .select(day.alias('Day'), nb_sum.alias('Sum_NB'), sb_sum.alias('Sum_SB')) 
     .group_by(SQL('Day')) 
     .order_by(SQL('Day'))) 
+0

謝謝,這幫助了很多。我也有點困惑如何訪問數據,並最終用for循環遍歷查詢。 –

相關問題