我正在编写一个网络应用程序,其中数据库查询来自两个选择框,一个与性别
有关,另一个与class_type
有关。在我的代码中,我有一个具有以下形式的基本查询
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)
有更好的方法来编写这个逻辑吗?
最佳答案
你可以这样做:
filters = {}
if sex != 'all':
filters['sex'] = sex
if class_type != 'all':
filters['class_type'] = class_type
rows = q.filter_by(**filters)
每个属性只需要一个条件,过滤器
的空字典将导致查询不包含 WHERE
子句。
关于python - 使用 2 个选择标准编写查询的更好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39669082/