Solution 1
Convert the UUID array uuid[]
to a text array text[]
select
p.name,
array(
select _i.item_id
from items _i
where _i.owner_id = p.person_id
)::text[] as item_ids
from persons p;
The from python code:
import psycopg2.extras
curs = conn.cursor(cursor_factory=extras.DictCursor) # To get rows in dictionary
curs.execute(my_query)
rows = curs.fetchall()
print(dict(row[0]))
Output:
{
"name": "Alex",
"item_ids": [
"db6c19a2-7627-4dff-a963-b90b6217cb11",
"db6c19a2-7627-4dff-a963-b90b6217cb11"
]
}
Solution 2
Register the UUID type so that the PostgreSQL uuid
can be converted to python uuid.UUID
(see python UUID docs) type.
import psycopg2.extras
psycopg2.extras.register_uuid()
After this, you can use the query without needing to convert to text array using ::text[]
.
select
p.name,
array(
select _i.item_id
from items _i
where _i.owner_id = p.person_id
) as item_ids
from persons p;
The output in DictRow will be like:
{
"name": "Alex",
"item_ids": [
UUID("db6c19a2-7627-4dff-a963-b90b6217cb11"),
UUID("db6c19a2-7627-4dff-a963-b90b6217cb11") # uuid.UUID data type
]
}