title: How to use case wen in db.session.query.filter_by()? Need to be optimized Python/Flask-SQLAlchemy
body: <p>If TestDate &gt;= '2021-01-01', filter type of <code>Type_One</code> items, if TestDate &lt; '2021-01-01' query type of <code>Type_Two</code> items, I use below <code>python</code> and <code>Flask-SQLAlchemy</code> to realize it, but it's ugly, how to optimize below code?</p>
  <pre><code>somewords = args.get('somewords')
  search = &quot;%{}%&quot;.format(somewords)
  TestDate = db.session.query(TestProject.test_date).filter(TestProject.id==id).first()
  
  if TestDate &gt;= '2021-01-01':
      test_code = db.session.query(TestCodeName.code). \
      distinct(TestCodeName.code, TestCodeName.type). \
      filter_by(type='Type_One'). \
      filter(or_(TestCodeName.code.contains(search))).all()
  else:
      test_code = db.session.query(TestCodeName.code). \
      distinct(TestCodeName.code, TestCodeName.type). \
      filter_by(type='Type_Two'). \
      filter(or_(TestCodeName.code.contains(search))).all()
  </code></pre>