0

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?

0

1 Answer 1

1

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.