Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I do a "starts with" query using SQL alchemy?

Tags:

I am learning to use SQL alchemy to connect to a mysql database. I want to pull records from the DB that start with a given string. I know that for simple equality all I need to do is this

queryRes = ses.query(Table).filter(Tablee.fullFilePath == filePath).all() result = [] 

How do I do something like this?

queryRes = ses.query(Table).filter(Table.fullFilePath.startsWith(filePath)).all() result = [] 

Maybe the query would look like this?

q = ses.query(Table).filter(Table.fullFilePath.like('path%')).all() 
like image 635
bernie2436 Avatar asked Nov 28 '13 15:11

bernie2436


People also ask

What does First () do in SQLAlchemy?

first() applies a limit of one within the generated SQL, so that only one primary entity row is generated on the server side (note this may consist of multiple result rows if join-loaded collections are present). Calling Query. first() results in an execution of the underlying query.

How does the querying work with SQLAlchemy?

Python Flask and SQLAlchemy ORM All SELECT statements generated by SQLAlchemy ORM are constructed by Query object. It provides a generative interface, hence successive calls return a new Query object, a copy of the former with additional criteria and options associated with it.

What does query all () return?

all() will return all records which match our query as a list of objects.

How do I SELECT in SQLAlchemy?

The select() method of table object enables us to construct SELECT expression. The resultant variable is an equivalent of cursor in DBAPI. We can now fetch records using fetchone() method. Here, we have to note that select object can also be obtained by select() function in sqlalchemy.


1 Answers

SQLAlchemy has a startswith column property, so it works exactly as you'd think:

queryRes = ses.query(Table).filter(Table.fullFilePath.startswith(filePath)).all() 
like image 61
John Lehmann Avatar answered Oct 22 '22 06:10

John Lehmann