I'd like to use psycopg2 to INSERT multiple rows and then return all the ids (in order) using a single query. This is what PostgreSQL's RETURNING extension is designed for, and it seems to work fine using cursor.execute:
cursor.execute(
"INSERT INTO my_table (field_1, field_2) "
"VALUES (0, 0), (0, 0) RETURNING id;"
)
print cursor.fetchall()
[(1,), (2,)]
Now, in order to pass in dynamically-generated data, it seems like cursor.executemany is the way to go:
data = [(0, 0), (0, 0)]
cursor.executemany(
"INSERT INTO my_table (field_1, field_2) "
"VALUES (%s, %s) RETURNING id;",
data
)
However, in that case, cursor.fetchall() produces the following:
[(4,), (None,)]
How do I get it to correctly return all the ids instead of just the one?