I'm trying to select all rows in a sql table where the first four characters of a text column match a certain string. (The backend database is a sqlite instance with limited column types, so bear with me)
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.
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)
. 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)
.
sqlalchemy
provides a endswith
functionality you could use in this case:
rows = SECtable.query.filter(SECtable.date.endswith(matchingString)).all()
You probably want to use SQLAlchemy's implementation of SQL's LIKE.
See the following documentation:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.