Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get primary key after inserting rows using sqlalchemy

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.

like image 611
mikhail Avatar asked Sep 05 '12 13:09

mikhail


2 Answers

the inserted_primary_key attribute is only functional for a single-row insert:

https://docs.sqlalchemy.org/en/latest/core/connections.html#sqlalchemy.engine.ResultProxy.inserted_primary_key

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.

like image 98
zzzeek Avatar answered Oct 16 '22 15:10

zzzeek


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

like image 34
dorvak Avatar answered Oct 16 '22 16:10

dorvak