I just ran into a rather unpleasant problem, and after testing, I found that NONE of the available answers is enough.
I saw various suggestions, but no one seems to be able to return the last inserted value for the auto_increment field in MySQL.
I saw examples that mention using session.flush () to add an entry and then get the id. However, this always returns 0.
I also saw examples that mention using session.refresh (), but this causes the following error: InvalidRequestError: Failed to update instance ''
What I'm trying to do seems insanely simple, but I can't understand the secret.
I use a declarative approach.
So 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 moment, the object f was transferred to the database and the unique identifier of the primary key was automatically assigned. However, I cannot find a way to get the value to use in some additional operations. I would like to do the following:
my_new_id = f.ModelID
I know that I can just do another query to search for ModelID based on other parameters, but I would prefer it to be possible.
I would really appreciate an understanding of the solution to this problem.
Thanks for the help in advance.