Last active
August 29, 2015 14:23
-
-
Save kwatch/fe96d6c13cd3c7d12c89 to your computer and use it in GitHub Desktop.
SQLAlchemyで、条件を動的に追加するときの書き方
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## | |
## SQLAlchemyで、条件を動的に追加するときの書き方 | |
## | |
## | |
## before | |
## | |
q = db.query(Model) \ | |
.filter(Model.created_at >= date(2015, 6, 1) | |
if kind: | |
q = q.filter(Model.kind==kind) | |
q = q.order_by(Model.created_at) | |
models = q.all() | |
## | |
## after | |
## | |
models = (db.query(Model) | |
.filter(Model.created_at >= date(2015, 6, 1)) | |
.filter(Model.kind==kind if kind else True) | |
.order_by(Model.created_at) | |
).all() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment