问题
so from this code:
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)
Notice that the variable rec, receives a query from the database, from this defined function I created in 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';
Now, suppose that the userID = 7, and the value of my table at userID (7) is:

But when I try to get that record, I receive this:
[["(300.00,30.00,3.33,underweight,21,0.00)"]]
To which I then found out (from thorough analysis), that this is a LIST OF TUPLES. Meaning, [(300.00,30.00,3.33,underweight,21,0.00)] is tuple[0] at the LIST, and (300.00,30.00,3.33,underweight,21,0.00) is element[0] at the TUPLE.
The problem is, that very (300.00,30.00,3.33,underweight,21,0.00) is recognized as ONE string or whatsoever, and it is deep down into the LIST of TUPLE. Is there other ways I could extract each element (cutting the string?) and place it into a proper list?
Like this: [300.00,30.00,3.33,underweight,21,0.00]
Much thanks. :)
回答1:
SELECT get_progressrecord(ID)
will return a single column of type record
.
SELECT * FROM get_progressrecord(ID)
will return multiple columns (matching your out
params).
As an aside, the fact that your output fields have no names might make your function a little difficult to work with. There's also an alternative syntax for RETURNS SETOF RECORD
which I find easier:
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
...
回答2:
You can use map function for this aim :
Demo :
>>> 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]]
来源:https://stackoverflow.com/questions/26157093/tuple-to-list-python-postgresql-return-type-of-setof-record