Get list of query results in Peewee
Asked Answered
L

2

7

Considering to switch from SQLAlchemy to peewee but have a fundamental question as I'm not able to find an example of this. I want to execute a query that returns a list of the matched objects. What works is get which returns a single record:

Topping.select().where(Topping.id==jalapenos.id).get()

What I want to get is a list of results for which all examples indicate that I should iterate. Is there a way to get a list of results from:

Topping.select(Topping).where(Topping.stock > 0)
Lichen answered 4/8, 2017 at 7:55 Comment(0)
P
21

A peewee query is lazily executed. It returns an iterator which must be accessed before the query will execute, either by iterating over the records or calling the execute method directly.

To force the query to execute immediately:

results = Topping.select().execute()

To convert query results to a list:

query = Topping.select().where(Topping.stock > 0)
toppings = list(query)
# OR
toppings = [t for t in query]

Note that you can greatly simplify your query for retrieving a single entity with:

Topping.get(Topping.id==jalapenos.id)
Pattani answered 16/8, 2017 at 19:30 Comment(0)
T
-2

Sometimes the execute statement also doesn't work. This works for me:

query = Topping.select().where(Topping.stock > 0)

result = query.dicts()
for row in result:
    print(row)
Train answered 1/12, 2023 at 20:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.