2014-10-02 50 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]]