0

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

1
  • Don't forget that you can easily debug the query generated by leaving off the "all()" and printing the resulting query. So, query = SECtable.query.filter(...); print query. Commented Oct 14, 2013 at 21:32

2 Answers 2

2

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()
Sign up to request clarification or add additional context in comments.

Comments

1

You probably want to use SQLAlchemy's implementation of SQL's LIKE.

See the following documentation:

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.