1
我正在编写一个Web应用程序,其中数据库查询来自两个选择框,一个是关于sex
而另一个是关于class_type
。在我的代码,我有具有以下形式使用2个选择标准编写查询的更好方法
q = User.query.with_entities(*(getattr(User, col) for col in cols))
而且取决于是否sex
和class_type
被选定为all
一个基本查询,我打破的情况如下
if sex=='all' and class_type=='all':
rows = q.all()
elif sex=='all' and class_type!='all':
rows = q.filter_by(class_type=class_type)
elif sex!='all' and class_type=='all':
rows = q.filter_by(sex=sex)
else:
rows = q.filter_by(sex=sex, class_type=class_type)
是否有更好的方法来写这个逻辑?