Home >Database >Mysql Tutorial >How to Correctly Filter Users by Age Range Using SQLAlchemy Date Fields?
SQLAlchemy: Filtering Date Fields
In a scenario where a User model defines a 'birthday' field as a Date data type, arise the need to filter users based on an age range. To achieve this with SQLAlchemy, one might initially consider and attempt:
query = DBSession.query(User).filter( and_(User.birthday >= '1988-01-17', User.birthday <= '1985-01-17') )
However, this attempt falls short of accuracy. The corrected filter is:
qry = DBSession.query(User).filter( and_(User.birthday <= '1988-01-17', User.birthday >= '1985-01-17') )
or equivalently:
qry = DBSession.query(User).filter(User.birthday <= '1988-01-17').\ filter(User.birthday >= '1985-01-17')
Alternatively, the between operator can be employed for the same purpose:
qry = DBSession.query(User).filter(User.birthday.between('1985-01-17', '1988-01-17'))
These approaches ensure that records within the specified date range are accurately selected.
The above is the detailed content of How to Correctly Filter Users by Age Range Using SQLAlchemy Date Fields?. For more information, please follow other related articles on the PHP Chinese website!