我想从指定的日期范围中获取行,但是当限制器为None(beg_date == None,fin_date == None)时,我想忽略一侧的范围。
例如: 如果beg_date =='2019-10-23'和fin_date == None我想得到 从2019-10-23至今的行。 如何使用SQLAlchemy做到这一点?
型号:
class MyModel(Model):
date = Column(Date)
代码:
beg_date = some_dict.get('beg_date')
fin_date = some_dict.get('fin_date')
session.query(MyModel).filter(MyModel.date.between(beg_date, find_date)
答案 0 :(得分:1)
You could build your date condition with Python conditions on start_date
and end_date
before building your whole query:
if start_date and end_date:
date_condition = MyModel.date.between(start_date, end_date)
elif start_date:
date_condition = MyModel.date > start_date
elif end_date:
date_condition = MyModel.date < end_date
else:
date_condition = true() # sqlalchemy.true()
session.query(MyModel).filter(date_condition)
I did not tested it but it should work with potential minor fixes.