2014-10-02 53 views
1

這樣:元組列表 - 從該代碼SETOF記錄的的Python/PostgreSQL的返回類型

from dosql import * 
import cgi 
import simplejson as json 

def index(req, userID): 
    userID = cgi.escape(userID) 

    get = doSql() 
    rec = get.execqry("select get_progressrecord('" + userID + "');", False) 

    return json.dumps(rec) 

注意,變量REC,接收來自數據庫的查詢時,從I PostgreSQL中創建此定義的函數:

現在
create or replace function 
    get_progressrecord(in int, out decimal(5,2), out decimal(5,2), out decimal(4,2), out text, out int, out decimal(4,2)) 
    returns setof record as 

$$ 
    select height, weight, bmi, healthStatus, age, changePercentage from progressrecord 
    where userID = $1; 
$$ 
language 'sql'; 

,假設用戶ID = 7,和我的表在用戶ID值(7): enter image description here

但是當我嘗試得到這個紀錄,我收到這樣的:

[ 「(300.00,30.00,3.33,體重過輕,21,0.00)」]]

要,然後我發現了(從深入分析)這是一個TUPLES列表。 含義, [(300.00,30.00,3.33,體重,21,0.00)]是元組[0]在列表,和 (300.00,30.00,3.33,體重,21,0.00)是元素[ 0]在TUPLE。

的問題是,非常(300.00,30.00,3.33,體重過輕,21,0.00)被認定爲ONE字符串或任何,它是內心深處到元組的列表。是否有其他方法可以提取每個元素(切割字符串?)並將其放入正確的列表中?

像這樣: [300.00,30.00,3.33,體重過輕,21,0.00]

許多感謝。 :)

回答

1

SELECT get_progressrecord(ID)將返回record類型的單個列。

SELECT * FROM get_progressrecord(ID)將返回多列(匹配您的out params)。

另外,輸出字段沒有名稱的事實可能會使您的函數有點難以使用。 RETURNS SETOF RECORD還有一個替代語法,我發現它更容易:

CREATE OR REPLACE FUNCTION get_progressrecord(int) 
    RETURNS TABLE(
    height decimal(5,2), 
    weight decimal(5,2), 
    bmi decimal(4,2), 
    healthStatus text, 
    age int, 
    changePercentage decimal(4,2) 
) AS 
    ... 
0

可以使用map功能在這個宗旨:

演示:

>>> tuple_list=[(300.00,30.00,3.33,'underweight',21,0.00),(300.00,30.00,3.33,'underweight',21,0.00)] 
>>> map(list,tuple_list) 
[[300.0, 30.0, 3.33, 'underweight', 21, 0.0], [300.0, 30.0, 3.33, 'underweight', 21, 0.0]]