'Trying to filter database using flask sqlalchemy that matches two fields but comes across key error

I'm new to flask and have been trying to filter my database(using the fields age and town). I'm getting type error which i assume is because of the fields integer and string and i'm stuck on how to resolve it. Here's my route code:


@app.route("/search/<string:town>/<int:age>", methods = ["GET"])
def search(town, age):
        search_result = User.query.filter(User.town.like('%'+town+'%'),User.age.like('%'+age+'%')) 
        Serializer = UserSchema(many = True)
        data = Serializer.dump(search_result)

        return jsonify(data), 200

i get this error which is pretty self explanatory.

TypeError: can only concatenate str (not &quot;int&quot;) to str //

Any help or workaround on how to filter my database using both the integer and string values passed in my endpoint route?



Solution 1:[1]

I assume your variable age is an integer: your code probably fails on '%'+age+'%' since it cannot concatenate the integer age with the strings '%'.

One possible solution can be to use .format(): User.age.like("%{}%".format(age)).

Does that solve the error for you?

EDIT: Since your input will be a string, you might also need to convert your database column values to a string in order to make this work, this would result in the following:

from sqlalchemy import cast, String

cast(User, String).age.like("%{}%".format(age))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1