Tuple to List - Python / PostgreSQL返回类型的SETOF记录

时间:2014-10-02 08:33:23

标签: python list postgresql tuples

所以从这段代码开始:

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从我在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';

现在,假设userID = 7,我在userID(7)的表的值是: enter image description here

但是当我试图获得该记录时,我收到了这个:

[[ “(300.00,30.00,3.33,体重,21,0.00)”]]

然后我发现(通过全面分析),这是一个 TUPLES列表。 含义, [(300.00,30.00,3.33,体重不足,21,0.00)] 是LIST的元组[0], (300.00,30.00,3.33,体重不足,21,0.00)是TUPLE的元素[0]。

问题是,非常(300.00,30.00,3.33,体重不足,21,0.00)被识别为 ONE 字符串或者其他任何内容,并且它深入到TUPLE的列表。还有其他方法可以提取每个元素(剪切字符串吗?)并将其放入正确的列表中?

像这样: 的 [300.00,30.00,3.33,体重,21,0.00]

非常感谢。 :)

2 个答案:

答案 0 :(得分:1)

SELECT get_progressrecord(ID)将返回record类型的单个列。

SELECT * FROM get_progressrecord(ID)将返回多个列(与out参数匹配)。

顺便说一句,输出字段没有名称这一事实可能会使您的函数难以使用。 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
  ...

答案 1 :(得分: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]]
相关问题