这是型号:
class User(Base):
...
birthday = Column(Date, index=True) #in database it's like '1987-01-17'
...
我想在两个日期之间进行过滤,例如选择间隔 18-30 年的所有用户。
如何用 SQLAlchemy 实现它?
我想到了:
query = DBSession.query(User).filter(
and_(User.birthday >= '1988-01-17', User.birthday <= '1985-01-17')
)
# means age >= 24 and age <= 27
我知道这是不正确的,但是如何正确呢?
最佳答案
事实上,您的查询是正确的,除了错字:您的过滤器排除了所有记录:您应该更改 <=
对于 >=
反之亦然:
qry = DBSession.query(User).filter(
and_(User.birthday <= '1988-01-17', User.birthday >= '1985-01-17'))
# or same:
qry = DBSession.query(User).filter(User.birthday <= '1988-01-17').\
filter(User.birthday >= '1985-01-17')
您也可以使用 between
:
qry = DBSession.query(User).filter(User.birthday.between('1985-01-17', '1988-01-17'))
https://stackoverflow.com/questions/8895208/
相关文章:
python - 如何在 Tesseract 和 OpenCV 之间进行选择?
python - 断言 numpy.array 相等性的最佳方法?
python - 如何从具有透明背景的 matplotlib 导出绘图?
python - 在系统范围内安装 pip 和 virtualenv 的官方 "preferred"
python - 如何使用 Pandas 创建随机整数的 DataFrame?
python - 使用 pandas GroupBy.agg() 对同一列进行多个聚合
python - Python 多处理模块的 .join() 方法到底在做什么?