Skip to content

Instantly share code, notes, and snippets.

entry = Entry.query.get(1)
entry.comments[0] # => <__main__.Comment object at 0x10184acd0>
comment = Comment.query.get(1)
comment.entry # => <__main__.Entry object at 0x101841a10>
class Entry(Base):
__tablename__ = 'entries'
id = Column(Integer, primary_key=True)
text = Column(String(200))
created_at = Column(DateTime, default=datetime.now, nullable=False)
comments = relationship('Comment', backref="entry", lazy="select") #<= lazyパラメータ
# relationship('Comment', lazy="select") (デフォルト)
# ------------------------------------------
# * 取得タイミング
# * プロパティにアクセスしたタイミング
#
# entry = Entry.query.filter_by(id=1).first()
# entry.comments # <- タイミングここ
#
# * 発行SQL
#
# relationship('Comment', lazy="immediate")
# ------------------------------------------
# * 取得タイミング
# * 親のモデルがロードされたタイミング一緒にSQL発行
# * lazy="select"とはタイミングが違うだけで発行してるSQLは一緒
#
# entry = Entry.query.filter_by(id=1).first() <- タイミングここ
# entry.comments
#
# * 発行SQL
# relationship('Comment', lazy="joined")
# ------------------------------------------
# * 取得タイミング
# * 親と子をJoinしたSQLを発行
# * ちなみに joinedload = eagarload は SQLAlchemyでは異音同義語(シノニム)
#
# entry = Entry.query.filter_by(id=1).first() <- タイミングここ
# entry.comments
#
# * 発行SQL
# relationship('Comment', lazy="subquery")
# ------------------------------------------
# * 取得タイミング
# * Entryを取得後、EntryのId列だけを取得して、そのId列のCommentのみを取得
#
# entry = Entry.query.filter_by(id=1).first() <- タイミングここ
# entry.comments
#
# * 発行SQL
# 1. SELECT * FROM entries WHERE entries.id = 1 LIMIT 1
# filter
# * メソッドをつなげて利用できる。
# => SELECT * From entries WHERE id = 1 AND text = "entry"
Entry.query.filter(Entry.id == 1).filter(Entry.text == "entry").all()
# filter_by
# * filterのシンタックスシュガー
Entry.query.filter_by(id=1, text="entry").all()
# get
# 結果取得を呼ばなければ単なるQueryオブジェクト
query = Entry.query.filter(Entry.id == 1) # => <class 'sqlalchemy.orm.query.Query'>
# クエリの付け加えもできる
if hoge == True:
query = query.filter(Entry.text == "entry")
# hoge = True : SELECT * FROM entries WHERE entries.id = %s AND entries.text = %s
# hoge = False : SELECT * FROM entries WHERE entries.id = %s
db_session.add(Entry(id=1, text="entrytext1"))
entry1 = Entry.query.filter_by(id=1).first()
# プロパティを変更
entry1.text = "hogehoge"
db_session.flush()
INSERT INTO entries (id, text, created_at) VALUES (%s, %s, %s)
(1, 'entrytext1', datetime.datetime(2012, 9, 15, 0, 39, 7, 668106))
SELECT entries.id AS entries_id, entries.text AS entries_text, entries.created_at AS entries_created_at
FROM entries
WHERE entries.id = %s
LIMIT %s
(1, 1)
UPDATE entries SET text=%s WHERE entries.id = %s