Given the following model
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(Text, nullable=False)
birthday = Column(Date)
You can filter columns in the query:
import datetime as dt
session.query(User).filter(User.name == 'Bob')
session.query(User).filter(User.birthday < dt.date(2000, 1, 1))
For the first case, there is a shortcut:
session.query(User).filter_by(name='Bob')
Filters can be composed using an AND relation by chaining the filter
method:
(session.query(User).filter(User.name.like('B%'))
.filter(User.birthday < dt.date(2000, 1, 1)))
Or more flexibly, using the overloaded bitwise operators &
and |
:
session.query(User).filter((User.name == 'Bob') | (User.name == 'George'))
Don't forget the inner parentheses to deal with operator precedence.