2020年2月11日 星期二

[ Python 常見問題 ] SQLAlchemy: how to filter date field?

Source From Here
Question
Here is model:
  1. class User(Base):  
  2.     ...  
  3.     birthday = Column(Date, index=True)   #in database it's like '1987-01-17'  
  4.     ...  
want to filter between two dates, for example to choose all users in interval 18-30 years. How to implement it with SQLAlchemy?

I think of:
  1. query = DBSession.query(User).filter(  
  2.     and_(User.birthday >= '1988-01-17', User.birthday <= '1985-01-17')  
  3. )   
  4.   
  5. # means age >= 24 and age <= 27  
I know this is not correct, but how to do correct?

How-To
In fact, your query is right except for the typo: your filter is excluding all records: you should change the <= for >= and vice versa:
  1. qry = DBSession.query(User).filter(  
  2.         and_(User.birthday <= '1988-01-17', User.birthday >= '1985-01-17'))  
  3. # or same:  
  4. qry = DBSession.query(User).filter(User.birthday <= '1988-01-17').\  
  5.         filter(User.birthday >= '1985-01-17')  
Also you can use between:
  1. qry = DBSession.query(User).filter(User.birthday.between('1985-01-17''1988-01-17'))  

1 則留言:

  1. Use this diet hack to drop 2 lb of fat in just 8 hours

    Well over 160 thousand men and women are using a easy and secret "liquids hack" to drop 2lbs each night while they sleep.

    It's scientific and works all the time.

    This is how to do it yourself:

    1) Get a glass and fill it with water half glass

    2) Then learn this strange hack

    and you'll be 2lbs skinnier the very next day!

    回覆刪除

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...