sqlalchemy flush() を実行して挿入された ID を取得しますか? 質問する

sqlalchemy flush() を実行して挿入された ID を取得しますか? 質問する

私は次のようなことをしたいのです:

f = Foo(bar='x')
session.add(f)
session.flush()

# do additional queries using f.id before commit()
print f.id # should be not None

session.commit()

しかし、試してみると、どうすればこれを機能させることができるのでしょうかf.id?None

ベストアンサー1

私も同じ問題に遭遇しましたが、テストした結果、これらの回答はどれも十分ではないことがわかりました。

現在、または sqlalchemy .6+ の時点では、非常に簡単な解決策があります (以前のバージョンに存在するかどうかはわかりませんが、存在すると思います)。

セッション.リフレッシュ()

したがって、コードは次のようになります。

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.

それがやり方です。

おすすめ記事