LoginSignup
6
5

More than 5 years have passed since last update.

SQLAlchemy メモ

Posted at

このエントリーの目的

SQLAlchemyをたまに使うと、使い方を忘れてしまうので使うたびにメモを取るためのエントリー

データ取得

instance = sessoin.query(Model).filter_by(Schema=Value)
instance = sessoin.query(Model).filter(Model.Schema==Value) #上記と同じ

instance.one() # 一つだけあるときにオブジェクトを返す。無い場合(NoResultFound)や、複数ある場合(MultipleResultsFound)エラーになる。

instance.first() # 無い場合、Noneが返る。1つ以上ある場合、何かしら一つのオブジェクトが返る

instance.all() # リストが返る

[m.Schema for m for instance] # のように、instanceはイテレータブル。

instance.count() # 件数が返る

データを格納

model_data = Model(Schema=Value)
sessoin.add(model_data)
model_data.Schema2 = Value2
transaction.commit()
model_data = sessoin.query(Model).filter_by(Schema=Value).first()
if model_data is None:
    model_data = Model(Schema=Value)
sessoin.add(model_data)
model_data.Schema2 = Value2
transaction.commit()
6
5
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
6
5