[Django]-SQLAlchemy – How do I see a primary key id for a newly created record?

3👍

 db.session.flush()
 #id is a Python builtin...
 id_= foo.id

What’s happening is that your original code before the flush was in your program only, nothing in db. The id column is likely an auto-generated field that gets assigned at insert time. Once the record is inserted (the flush writes changes to the db), SQLAlchemy basically does a select id from <inserted> and returns the results (various databases use various mechanisms for that). And now you have id populated.

Commits and rollbacks are different in nature from flush. They affect what’s already in the db.

Also, flagging your comment I need to use it while adding other records in DB. I explained how to get the id field value, but that doesn’t mean it’s appropriate to use in your wider context. SQLAlchemy has different ways to link records before flush().

Leave a comment