rgb
rgb

Reputation: 3294

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. (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

Upvotes: 0

Views: 1994

Answers (2)

mata
mata

Reputation: 69082

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()

Upvotes: 2

Related Questions