We use Python sets extensively and need to insert data from sets into our Postgres DB, which doesn't have a similar data type. We'd like to insert all sets into the DB as arrays. We could do that by wrapping all sets with list(), but it would be nice to write a simple psycopg2 adaptor instead. I've looked at the docs, but it's unclear how to do it.
Add a comment
|
1 Answer
You can do it by registering an adapter for the set type and use the adapt function to treat the set as a list. This'll give the set the necessary getquoted() function from the list, which'll turn it into ARRAY[x,y,...] in the SQL string. See the code below.
from psycopg2.extensions import register_adapter, adapt
def adapt_set(my_set):
return adapt(list(my_set))
register_adapter(set, adapt_set)
1 Comment
pir
Figured out the solution after drafting the question so tried the Q&A style answer. Hope it's helpful to anyone!