获取 "declarative_base()" 中最后插入的记录主键

Get last inserted record's Primary Key in "declarative_base()"

我想获取上次插入的 主键,我已经知道两种方法:

1) "lastrowid" 与 "raw SQL"

from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String, text

engine = create_engine('sqlite://')

meta = MetaData()

tbl = Table('tbl', meta,
    Column('f1', Integer, primary_key=True),
    Column('f2', String(64))
)

tbl.create(engine)

sql = text("INSERT INTO tbl VALUES (NULL, 'some_data')")
res = engine.execute(sql)

print(res.lastrowid)

2) "inserted_primary_key" 与 "insert()"

from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String

engine = create_engine('sqlite://')

meta = MetaData()

tbl = Table('tbl', meta,
    Column('f1', Integer, primary_key=True),
    Column('f2', String(64))
)

tbl.create(engine)

ins = tbl.insert().values(f2='some_data')
res = engine.execute(ins)

print(res.inserted_primary_key)

但我的问题是"declarative_base()"

from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

engine = create_engine('sqlite://')

Base = declarative_base()
Session = sessionmaker(bind=engine)
session = Session()

class TBL(Base):
    __tablename__ = 'tbl'

    f1 = Column(Integer, primary_key=True)
    f2 = Column(String(64))

Base.metadata.create_all(engine)

rcd = TBL(f2='some_data')

session.add(rcd)
session.commit()

如果我这样做:

res = session.add(rcd)

它给我"None"。或者如果我这样做:

res = session.commit()

同样的事情发生了。我的问题是:

在 "declarative_base()" 的情况下,是否有访问 "lastrowid" 或 "inserted_primary_key" 的好方法?

最好的方法是什么?

调用session.commit()后,访问rcd.f1将return其生成的主键。 SQLAlchemy 在 expired by the commit.

之后自动从数据库重新加载对象