SQLAlchemy:如何过滤date字段?
这里是模型:
class User(Base): ... birthday = Column(Date, index=True) #in database it's like '1987-01-17' ...
我想在两个date之间过滤,例如select间隔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
我知道这是不正确的,但如何做到正确?
提前致谢!
事实上,你的查询是正确的,除了错字:你的filter是排除所有logging:你应该改变<=
for >=
,反之亦然:
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')
你也可以使用:
qry = DBSession.query(User).filter(User.birthday.between('1985-01-17', '1988-01-17'))
from app import SQLAlchemyDB as db Chance.query.filter(Chance.repo_id==repo_id, Chance.status=="1", db.func.date(Chance.apply_time)<=end, db.func.date(Chance.apply_time)>=start).count()
它等于:
select count(id) from Chance where repo_id=:repo_id and status='1' and date(apple_time) <= end and date(apple_time) >= start
希望可以帮助你。