python SQLAlchemy 在提交前使用自动增量获取主键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/620610/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 20:29:16  来源:igfitidea点击:

SQLAlchemy Obtain Primary Key With Autoincrement Before Commit

pythonsqlsqlalchemy

提问by Jacob Gabrielson

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.

我想在一个事务中放置两个操作,但是其中一个操作将取决于在前一个操作中分配的主键。

回答by Jacob Gabrielson

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

你不需要commit,你只需要flush。这是一些示例代码。在调用flush之后,您可以访问分配的主键。请注意,这是使用 SQLAlchemy v1.3.6 和 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()

回答by achinda99

You can use multiple transactions and manage it within scope.

您可以使用多个事务并在范围内对其进行管理。