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))
all() will return all records which match our query as a list of objects.
It does return an empty list.
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.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With