Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy - check if query found any results

How can I check if a query found any results?

result = db.engine.execute(sql, id=foo)
// check if result has rows ...
for row in result:
  ...

Tried this:

if result is None:
    print("reuslt is None!")

and checked length:

print("result len", len(result))
like image 705
el_pup_le Avatar asked Jul 08 '18 00:07

el_pup_le


People also ask

What does query all () return?

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

What does SQLAlchemy all () return?

It does return an empty list.

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?

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.


2 Answers

all() may be quite slow for some databases, count() is better but first() is even faster for large databases and complex queries. For example:

x = db.session.query(Post).filter(Post.read==True).first() is not None
like image 186
Jelmer Avatar answered Sep 23 '22 16:09

Jelmer


len is the better way. You were near:

print("result len", len(result.all()))

You cant access to a BaseQuery len if you dont get all of its elements.

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

like image 29
Víctor López Avatar answered Sep 24 '22 16:09

Víctor López