我正在尝试选择 sql 表中文本列的前四个字符与某个字符串匹配的所有行。(后端数据库是一个sqlite实例,列类型有限,请多多包涵)
我为选择编写的代码是这样的:
rows = SECtable.query.filter(str(SECtable.date)[:4] == str(matchingString)).all()
我在这里做错了什么?查询从不匹配任何行
我正在尝试选择 sql 表中文本列的前四个字符与某个字符串匹配的所有行。(后端数据库是一个sqlite实例,列类型有限,请多多包涵)
我为选择编写的代码是这样的:
rows = SECtable.query.filter(str(SECtable.date)[:4] == str(matchingString)).all()
我在这里做错了什么?查询从不匹配任何行
如果你使用SECtable.date == 'some_string',这会产生一个表达式 ( sqlalchemy.sql.expression.BinaryExpression),当你执行查询时会计算它。
str(SECtable.date)[:4] == str(matchingString)立即进行评估,它产生SECtable.date(我猜'SECTable.date') 的字符串表示,并将除第一个字符之外的所有字符与str(matchingString). 所以你在这里写的基本上是:
'able.date' == str(matchingString)
这可能会评估为假,所以你最终得到filter(False).
sqlalchemy提供了endswith您可以在这种情况下使用的功能:
rows = SECtable.query.filter(SECtable.date.endswith(matchingString)).all()
您可能想要使用 SQLAlchemy 的 SQL LIKE 实现。
请参阅以下文档: