Get primary key after inserting rows using sqlalchemy
Solution 1
the inserted_primary_key attribute is only functional for a single-row insert:
This only applies to single row insert() constructs which did not explicitly specify Insert.returning().
this is due to a widely prevalent limitation in database client libraries including all Python DBAPIs where only one "last inserted id" attribute is left available at a time.
Solution 2
Maybe your ResultsProxy is a list or list-like object, so you should iterate over the elements=db-rows of that object:
for e in topic_res:
print e.inserted_primary_key
EDIT: the method "inserted_primary_key" seems to work only for single-row insertions. See http://docs.sqlalchemy.org/en/rel_0_6/core/connections.html#sqlalchemy.engine.base.ResultProxy.inserted_primary_key
Related videos on Youtube
mikhail
Updated on September 15, 2022Comments
-
mikhail over 1 year
I'm inserting many rows with sqlalchemy:
connection = engine.connect() topic_res = connection.execute(message_topics.insert(),[ { 'mt_date': time.time(), 'mt_title': title, 'mt_hasattach':u'0', 'mt_starter_id':member.member_id, 'mt_start_time': time.time(), 'mt_last_post_time': time.time(), 'mt_invited_members': u'a:0:{}', 'mt_to_count': u'1', 'mt_to_member_id':member.member_id, 'mt_replies': u'1', } for member in members ]) topic_res.inserted_primary_key
when I try to get inserted primary keys, and I am getting:
AttributeError: 'MySQLExecutionContext_mysqldb' object has no attribute 'inserted_primary_key', but topic_res is 'ResultProxy' object due to debug.
So if I insert only one row I can get topic_res.inserted_primary_key.