Skip to content

Instantly share code, notes, and snippets.

@kwatch
Last active August 29, 2015 14:23
Show Gist options
  • Save kwatch/fe96d6c13cd3c7d12c89 to your computer and use it in GitHub Desktop.
Save kwatch/fe96d6c13cd3c7d12c89 to your computer and use it in GitHub Desktop.
SQLAlchemyで、条件を動的に追加するときの書き方
##
## 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