azndude956
azndude956

Reputation: 29

Converting JSON object to usable sqlalchemy filter statements

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!

Upvotes: 2

Views: 843

Answers (1)

davidism
davidism

Reputation: 127390

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

Upvotes: 1

Related Questions