Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23131

Get last inserted value from MySQL using SQLAlchemy

$
0
0

I want to return the last inserted value for an auto_increment field in MySQL.

I have seen examples that mention the use of session.flush() to add the record and then retrieve the id. However that always seems to return 0.

I have also seen examples that mention the use of session.refresh() but that raises the following error:

InvalidRequestError: Could not refresh instance '<MyModel....>'

My code looks something like this:

class Foo(Base):    __tablename__ = 'tblfoo'    __table_args__ = {'mysql_engine':'InnoDB'}    ModelID = Column(INTEGER(unsigned=True), default=0, primary_key=True, autoincrement=True)    ModelName = Column(Unicode(255), nullable=True, index=True)    ModelMemo = Column(Unicode(255), nullable=True)f = Foo(ModelName='Bar', ModelMemo='Foo')session.add(f)session.flush()

At this point, the object f has been pushed to the DB, and has been automatically assigned a unique primary key id. However, I can't seem to find a way to obtain the value to use in some additional operations. I would like to do the following:

my_new_id = f.ModelID

I know I could simply execute another query to lookup the ModelID based on other parameters but I would prefer not to if at all possible.


Viewing all articles
Browse latest Browse all 23131

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>