Sqlalchemy: Purpose of .all()

Question:

What is the use of .all(). When the following function

def showRestaurants():
restaurants = session.query(Restaurant)
return render_template('restaurant.html',restaurants=restaurants)

Returns the same result as this function

def showRestaurants():
restaurants = session.query(Restaurant).all()
return render_template('restaurant.html',restaurants=restaurants)

For this restaurant.html file

<html>
<body>
<h1> Restaurants </h1>

{% for x in restaurants %}
</br>

{% endfor %}
</body>
</html>
Asked By: Mustafa Khan

||

Answers:

it just executes your query and returns a list with results, see https://docs.sqlalchemy.org/en/rel_1_0/orm/query.html#sqlalchemy.orm.query.Query.all

alternatively you can execute the query manually:

session.execute(Restaurant.select())
Answered By: Paweł Kordowski

First example returns Query object and you can apply additional methods on it, such as all() – it will return results represented by that Query as a list.

Query object works on each row before give it, while the second works on all rows, before starting to give them.

Answered By: midori
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.