【问题标题】:better way to write queries with 2 selection criteria使用 2 个选择标准编写查询的更好方法
【发布时间】:2016-09-23 20:32:22
【问题描述】:

我正在编写一个网络应用程序,其中数据库查询来自两个选择框,一个是关于sex,另一个是关于class_type。在我的代码中,我有一个具有以下形式的基本查询

q = User.query.with_entities(*(getattr(User, col) for col in cols))    

并且根据sexclass_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)

有没有更好的方法来编写这个逻辑?

【问题讨论】:

    标签: python sql sqlalchemy flask-sqlalchemy


    【解决方案1】:

    你可以这样做:

    filters = {}
    if sex != 'all':
        filters['sex'] = sex
    if class_type != 'all':
        filters['class_type'] = class_type
    rows = q.filter_by(**filters)
    

    每个属性只需要一个条件,filters 的空字典将导致查询没有WHERE 子句。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多