【问题标题】:Flask sqlachemy handling multiple filtersFlask sqlalchemy 处理多个过滤器
【发布时间】:2021-04-04 11:13:31
【问题描述】:

我想知道如何处理多个过滤器?例如我们有

*table*
class ExampleTable(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(90))
    date = db.Column(db.DateTime)

我们得到的 JSON 数据是

{
  "title": "test",
  "date": "2020-12-27"
}

为了执行过滤查询,我所做的如下

if title != '' and date != '':
    data = [ example_json for example_json in ExampleTable.query.filter(ExampleTable.title.contains(json['title']).filter(ExampleTable.date.contains(json['date']).all() ]
elif title != '':
    data = [ example_json for example_json in ExampleTable.query.filter(ExampleTable.title.contains(json['title']).all() ]
else:
    data = [ example_json for example_json in ExampleTable.query.all() ]

return data

这只是一个示例,但您可以看到它的重复性,如果我们有 5 或 10 个过滤器单独检查每个过滤器,那么这样简单的任务需要几个小时

在 SQL 中处理多个过滤器查询的正确方法是什么?

【问题讨论】:

    标签: python flask-sqlalchemy


    【解决方案1】:

    filter 方法返回 query 实例,因此您可以重复添加过滤器,如下所示:

    query = ExampleTable.query()
    if title:
        query = query.filter(ExampleTable.title.contains(json['title'])
    if date:
        query = query.filter(ExampleTable.title.contains(json['date'])
    result = query.all()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-03-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-04
      • 1970-01-01
      • 1970-01-01
      • 2018-02-18
      相关资源
      最近更新 更多