Skip to content

Instantly share code, notes, and snippets.

@tell-k
Created September 14, 2012 15:24
Show Gist options
  • Save tell-k/3722608 to your computer and use it in GitHub Desktop.
Save tell-k/3722608 to your computer and use it in GitHub Desktop.
# 結果取得を呼ばなければ単なる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
# サブクエリ
sub_query = Entry.query.filter_by(text="entry").subquery()
db_session.query(sub_query).filter_by(id=1).all()
# SELECT *
# FROM (
# SELECT * FROM entries
# WHERE entries.text = "entry"
# ) AS anon_1
# WHERE anon_1.id = 1
# Union
q1 = Entry.query.filter_by(id=1)
q2 = Entry.query.filter_by(id=2)
q1.union(q2).all()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment