简体   繁体   English

python中的简单SQLAlchemy查询过滤器

[英]Simple SQLAlchemy query filter in python

I'm trying to select all rows in a sql table where the first four characters of a text column match a certain string. 我试图在sql表中选择其中文本列的前四个字符与某个字符串匹配的所有行。 (The backend database is a sqlite instance with limited column types, so bear with me) (后端数据库是具有有限列类型的sqlite实例,请耐心等待)

The code I've written for the select is this: 我为选择编写的代码是这样的:

    rows = SECtable.query.filter(str(SECtable.date)[:4] == str(matchingString)).all()

What am I doing wrong here? 我在这里做错了什么? The query never matches any rows 查询从不匹配任何行

If you use SECtable.date == 'some_string' , this produces an expression ( sqlalchemy.sql.expression.BinaryExpression ), which will be evaluated when you execute the query. 如果使用SECtable.date == 'some_string'SECtable.date == 'some_string'生成一个表达式( sqlalchemy.sql.expression.BinaryExpression ),将在执行查询时对其进行评估。

str(SECtable.date)[:4] == str(matchingString) is evaluated immediately, it produces the string representation of SECtable.date (i'd guess 'SECTable.date' ), and compares all but the fist for characters to str(matchingString) . str(SECtable.date)[:4] == str(matchingString)被立即求值,它产生SECtable.date的字符串表示SECtable.date (我猜是'SECTable.date' ),并将除拳头以外的所有字符进行比较str(matchingString) so what you're writing here is basically: 所以你在这里写的基本上是:

'able.date' == str(matchingString)

which will probably evaluate to false, so you end up with filter(False) . 可能会得出false的结果,所以最终得到filter(False)

sqlalchemy provides a endswith functionality you could use in this case: sqlalchemy提供endswith你可以在这种情况下使用的功能:

rows = SECtable.query.filter(SECtable.date.endswith(matchingString)).all()

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

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