当我创建一个带有自动递增主键的表时,是否有办法获得主键(即保留主键)而不实际提交?
我想在事务中放置两个操作,但其中一个操作将取决于在上一个操作中分配了哪个主键.
你不需要commit
,你只需要flush
.这是一些示例代码.在调用flush之后,您可以访问已分配的主键.注意这是SA 0.4.8.
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()