14
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【SQLAlchemy】insertしたレコードのidを取得・利用

Posted at

この記事はなに

SQLAlchemyにおいて新規作成したレコードのid値を取得・利用する方法を書いたメモ

前置き

# Userテーブルのレコードを新規作成

# 続けて作成したuserのidをuser_idとしてauthorizationレコードを作成

というような操作をしたい場合、
みんな大好きRuby on RailsのORMであるActive Recordなどでは

user = User.create!(test_column=‘test’)
# user.id -> 2

# 続けてuser.idをuser_idとしてauthorizationレコードを作成

と直感的に書けるが、

FlaskやBottleなどのPythonの軽量フレームワークでしばしば使用されるORMであるSQLAlchemyでは書き方が直感的ではない気がしたので雑メモする

本題

SQLAlchemyのinsertにおいてidが確定するタイミングは

db = SQLAlchemy()

user = User(test_column=‘test’)
db.session.add(user)
db.session.commit()

のcommit部分なので

user = User(test_column=‘test’)
# user.id -> None

db.session.add(user)
# user.id -> None

db.session.commit()
# user.id -> 2

# 続けてuser.idをuser_idとしてauthorizationレコードを作成

のように(考えてみれば当たり前だが) commit()したタイミングで、userが変化してid が取得できるようになる。

また、もちろんネストを使って以下のように書いても

db.session.begin_nested()
# user.id -> 2

とidが確定する。

14
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?