简体   繁体   English

使用 sqlalchemy 和 postgresql 自定义过滤器查询 flask

[英]custom filter query for flask using sqlalchemy and postgresql

I am trying to make filter in postgre sql table that have varchar and integer column.我正在尝试在具有 varchar 和 integer 列的 postgre sql 表中创建过滤器。 And I need to apply filter.我需要应用过滤器。 For example I have a category table as below:例如,我有一个类别表如下:

id    name    rank
1     test1   1
2     test2   2
3     test3   3

And I want to apply filter in slqalchemy in flask as below:我想在 flask 的 slqalchemy 中应用过滤器,如下所示:

filter_text = "%{}%".format(request.args.get('search[value]'))
filter_int = request.args.get(['search[value]')
if(filter_text):
    categories = Category.query.filter(
        (Category.category_name.like(filter_text)) | 
        (Category.rank == filter_int)
    ).all()
else:
    categories = Category.query.all()

I get search[value] from the input field which can be both integer and alphabet or both.我从输入字段中获取搜索[值],它可以是 integer 和字母表或两者。 When I run code and pass alphabet I get error while I pass search['value'] = 't':当我运行代码并传递字母表时,我在传递搜索 ['value'] = 't' 时出错:

sqlalchemy.exc.DataError: (psycopg2.errors.InvalidTextRepresentation) invalid input syntax for integer: "t" 

I know the issue is due to alphabet passed in rank column which is integer. But I want to search in all column using same single input field.我知道问题是由于字母表在等级列中传递,即 integer。但我想使用相同的单个输入字段在所有列中进行搜索。

you need to typecast the query column based on your condition.您需要根据您的条件对查询列进行类型转换。 Thanks谢谢

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM