Reputation: 1
I am wondering how are multiple filters handled? for example we have
*table*
class ExampleTable(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(90))
date = db.Column(db.DateTime)
and JSON data we get is
{
"title": "test",
"date": "2020-12-27"
}
for performing filter queries what i've done is following
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
This is just example but you can see how repetitive it gets and if we have 5 or 10 filters checking each one individually against each other would take hours for such simple task
What is proper way to handle multiple filter queries in SQL?
Upvotes: 0
Views: 296
Reputation: 55589
The filter
methods return query
instances, so you can add filters repeatedly, like this:
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()
Upvotes: 1