Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy: create an intentionally empty query?

What's the best way to create an intentionally empty query in SQLAlchemy?

For example, I've got a few functions which build up the query (adding WHERE clauses, for example), and at some points I know that the the result will be empty.

What's the best way to create a query that won't return any rows? Something like Django's QuerySet.none().

like image 259
David Wolever Avatar asked Apr 27 '12 05:04

David Wolever


People also ask

How do I check if a SQLAlchemy query is empty?

Compare result with None is ok if you want to know if its empty.

Is SQLAlchemy text safe?

The python package SQLAlchemy was scanned for known vulnerabilities and missing license, and no issues were found. Thus the package was deemed as safe to use.

What is subquery in SQLAlchemy?

The statement ends by calling subquery() , which tells SQLAlchemy that our intention for this query is to use it inside a bigger query instead of on its own.

What is an Engine in SQLAlchemy?

The Engine is the starting point for any SQLAlchemy application. It's “home base” for the actual database and its DBAPI, delivered to the SQLAlchemy application through a connection pool and a Dialect , which describes how to talk to a specific kind of database/DBAPI combination.


2 Answers

If you need the proper return type, just return session.query(MyObject).filter(sqlalchemy.sql.false()).

When evaluated, this will still hit the DB, but it should be fast.

If you don't have an ORM class to "query", you can use false() for that as well: session.query(sqlalchemy.false()).filter(sqlalchemy.false())

like image 121
Dag Høidahl Avatar answered Nov 01 '22 08:11

Dag Høidahl


db_session(YourModel).query.filter(False)
like image 7
gaozhidf Avatar answered Nov 01 '22 09:11

gaozhidf