1
0

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 3 years have passed since last update.

SQLAlchemyのwith_loader_criteria句を使うと地味に便利(>=1.4)

Posted at

何これ

SQLAlchemy 1.4以上で使える with_loader_criteria() オプションを使うとかなり楽になる
(2021年3月にリリースされました-> Changelog)

良い事

  • One to ManyでJOINする相手のテーブルをfilterしたい時に記述量が減る
  • lazy の指定によらず何にでも効いてくれる

チャットルームとチャット参加者を管理するテーブルがあったとします。
また、2者の関係は relationship('ChatJoinedUser', backref="chat_rooms", lazy='joined') で定義されています。

chat_rooms = session.query(ChatRoom).filter(and_(
    ChatRoom.account_id == current_user.account_id,
    ChatRoom.is_ended == False
)).options(with_loader_criteria(
    ChatJoinedUser, ChatJoinedUser.attending_status != AttendingStatus.leaving)).all()
SELECT 
  (中略)
FROM 
  chat_rooms 
LEFT OUTER JOIN 
  chat_joined_users AS chat_joined_users_1 
ON 
  chat_rooms.chat_id = chat_joined_users_1.chat_id 
AND 
  chat_joined_users_1.attending_status != 'XXXXXX' 
WHERE 
  chat_rooms.account_id = 'YYYYYY' 
AND 
  chat_rooms.is_ended = false

発行されるクエリはこんな感じになる。
SQLAlchemyはeager loading(積極的読み込み)に関するテクニックがバージョンによって違ったりrelationshipによっては使えなかったりするので、この関数が出てきてだいぶ楽になった。

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?