2

After a query with Python's psycopg2

SELECT 
    id,
    array_agg(еnty_pub_uuid) AS ptr_entity_public 
FROM table
GROUP BY id

I get returned an array:

{a630e0a3-c544-11ea-9b8c-b73c488956ba,c2f03d24-2402-11eb-ab91-3f8e49eb63e7} 

How can I parse this to a list in python?

Is there a builtin function in psycopg2?

0

2 Answers 2

2

psycopg2 cares about type conversations between python and postgres:

import psycopg2

conn = psycopg2.connect("...")
cur = conn.cursor()
cur.execute(
    "select user_id, array_agg(data_name) from user_circles where user_id = '81' group by user_id"
)
res = cur.fetchall()
print(res[0])
print(type(res[0][1]))

Out:

('81', ['f085b2e3-b943-429e-850f-4ecf358abcbc', '65546d63-be96-4711-a4c1-a09f48fbb7f0', '81d03c53-9d71-4b18-90c9-d33322b0d3c6', '00000000-0000-0000-0000-000000000000'])
<class 'list'>
Sign up to request clarification or add additional context in comments.

Comments

0

you need to register the UUID type for python and postgres to infer types.


import psycopg2.extras
psycopg2.extras.register_uuid()
sql = """
SELECT 
    id,
    array_agg(еnty_pub_uuid) AS ptr_entity_public 
FROM table
GROUP BY id
"""
cursor = con.cursor()
cursor.execute(sql)
results = cursor.fetchall()

for r in results:
    print(type(r[1]))

1 Comment

Theres other parameters in the query. The question is how can I read this array in python?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.