尝试使用 Flask sqlalchemy 过滤数据库,该数据库匹配两个字段,但遇到关键错误
我是烧瓶新手,一直在尝试过滤我的数据库(使用字段年龄和城镇)。我收到类型错误,我认为这是由于字段整数和字符串造成的,我一直不知道如何解决它。这是我的路线代码:
@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
我收到这个错误,这是非常不言自明的。
TypeError: can only concatenate str (not "int") to str //
有关如何使用端点路由中传递的整数和字符串值来过滤数据库的任何帮助或解决方法?
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 "int") to str //
Any help or workaround on how to filter my database using both the integer and string values passed in my endpoint route?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我假设您的变量
age
是一个整数:您的代码可能在'%'+age+'%'
上失败,因为它无法连接整数age
与字符串'%'
。一种可能的解决方案是使用
.format()
:User.age.like("%{}%".format(age))
。这能为您解决错误吗?
编辑:由于您的输入将是一个字符串,您可能还需要将数据库列值转换为字符串才能完成此操作,这将导致以下结果:
I assume your variable
age
is an integer: your code probably fails on'%'+age+'%'
since it cannot concatenate the integerage
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: