Python SQLAlchemy get retruning ID after inserting
<p>I want to get the ID of the last inserted record after inserting in postgresql using SQLAlchemy. Here is code,</p>

<pre><code>insert_record = {list of data}
result = connection.execute(tbl_example.insert().returning(tbl_example.c.id), insert_record)
print result.id
</code></pre>

<p>The inserting does fine but I can't seem to get the ID of the last inserted, I get the following error,</p>

<blockquote>
  <p>AttributeError: 'ResultProxy' object has no attribute 'id'</p>
</blockquote>

<p>Where is the return ID located in the returning object? </p>

<p>It's located directly in returning object. There is example from <a href="http://docs.sqlalchemy.org/en/latest/core/dml.html" rel="nofollow">documentation:</a></p>

<pre><code>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)
</code></pre>

<p>Also, <code>ResultProxy</code> <a href="http://docs.sqlalchemy.org/en/latest/core/connections.html#sqlalchemy.engine.ResultProxy" rel="nofollow">supports</a> accessing via positon (as in example) and via name. So, you can use something like: <code>row_id = result['id']</code>.</p>

python mysql postgresql sqlalchemy