Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
591 views
in Technique[技术] by (71.8m points)

python - SQLAlchemy Obtain Primary Key With Autoincrement Before Commit

When I have created a table with an auto-incrementing primary key, is there a way to obtain what the primary key would be (that is, do something like reserve the primary key) without actually committing?

I would like to place two operations inside a transaction however one of the operations will depend on what primary key was assigned in the previous operation.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You don't need to commit, you just need to flush. Here's some sample code. After the call to flush you can access the primary key that was assigned. Note this is with SQLAlchemy v1.3.6 and Python 3.7.4.

from sqlalchemy import *
import sqlalchemy.ext.declarative

Base = sqlalchemy.ext.declarative.declarative_base()

class User(Base):
    __tablename__ = 'user'
    user_id = Column('user_id', Integer, primary_key=True)
    name = Column('name', String)

if __name__ == '__main__':
    import unittest
    from sqlalchemy.orm import *
    import datetime

    class Blah(unittest.TestCase):
        def setUp(self):
            self.engine = create_engine('sqlite:///:memory:', echo=True)
            self.sessionmaker = scoped_session(sessionmaker(bind=self.engine))
            Base.metadata.bind = self.engine
            Base.metadata.create_all()
            self.now = datetime.datetime.now()

        def test_pkid(self):
            user = User(name="Joe")
            session = self.sessionmaker()
            session.add(user)
            session.flush()
            print('user_id', user.user_id)
            session.commit()
            session.close()

    unittest.main()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...