I want to get the ID of the last inserted record after inserting in postgresql using SQLAlchemy. Here is code,
insert_record = {list of data}
result = connection.execute(tbl_example.insert().returning(tbl_example.c.id), insert_record)
print result.id
The inserting does fine but I can't seem to get the ID of the last inserted, I get the following error,
AttributeError: 'ResultProxy' object has no attribute 'id'
Where is the return ID located in the returning object?
It's located directly in returning object. There is example from documentation:
stmt = table.update().\
where(table.c.data == 'value').\
values(status='X').\
returning(table.c.server_flag,
table.c.updated_timestamp)
for server_flag, updated_timestamp in connection.execute(stmt):
print(server_flag, updated_timestamp)
Also, ResultProxy supports accessing via position (as in example) and via name. So, you can use something like row_id = row['id'] where:
for row in connection.execute(stmt):
row_id = row['id']
row_id = row.id
row_id = row[0]
print(row_id)
Note that not all database backends support this feature. From the documentation:
Note that not all databases/DBAPIs support RETURNING. For those backends with no support, an exception is raised upon compilation and/or execution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With