Я только что столкнулся с той же проблемой, и после тестирования я обнаружил, что НИКАКОГО из этих ответов не достаточно.
В настоящее время, или в sqlalchemy .6+, есть очень простое решение (я не знаю, существует ли оно в предыдущей версии, хотя я предполагаю, что оно существует):
session.refresh ()
Итак, ваш код будет выглядеть примерно так:
f = Foo(bar=x)
session.add(f)
session.flush()
# At this point, the object f has been pushed to the DB,
# and has been automatically assigned a unique primary key id
f.id
# is None
session.refresh(f)
# refresh updates given object in the session with its state in the DB
# (and can also only refresh certain attributes - search for documentation)
f.id
# is the automatically assigned primary key ID given in the database.
Вот как это сделать.