2

From the flask component I have request that I call:

request_json = request.get_json() 

This is a JSON object containing the following:

{'filter1' : '123', 'filter2' : '456', 'filter3' : '789' }

Also these filters can vary in size depending on the front end user. It could be just one filter or multiple.

I am wondering how you would convert an object such as this to a query that would be usable? I believe or_() and and_() is what I need to use to build the filter. Is it possible to do something such as...

query.filter_by(and_(*request_json))

I am very new to the entire tech stack...any help would be appreciated!

1 Answer 1

1

filter_by takes keyword arguments to perform basic equality filters. Remove the and_ and splat the dict directly into filter_by.

query.filter_by(**request_json)

This does no validation on the keys or values, however. So if someone passed in 'fish': 3 and there was no "fish" column, or passed in 'column4': 'abc' and column4 is actually an array type, you would get an error.

So it's probably safer and more straightforward to validate and do the filtering manually.

query = MyModel.query

if 'column1' in data:
    try:
        value = int(data['column1'])
    except (TypeError, ValueError):
        pass
    else:
        query = query.filter(MyModel.column1 == value)

if 'column2' in data:
    try:
        value = datetime.utcfromtimestamp(int(data['column2']))
    except (TypeError, ValueError):
        pass
    else:
        query = query.filter(MyModel.column2 >= value)

# etc.

return query
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.