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)
Queries in peewee are constructed one piece at a time. The “pieces” of a peewee query are generally representative of clauses you might find in a SQL query.
See namedtuples (), tuples () , dicts () for more information. By default peewee will cache the rows returned when iterating over a Select query. This is an optimization to allow multiple iterations as well as indexing and slicing without causing additional queries.
Peewee supports the inclusion of common table expressions (CTEs) in all types of queries. CTEs may be useful for: Factoring out a common subquery. Grouping or filtering by a column derived in the CTE’s result set.
In addition, Peewee also offers Model.bulk_update (), which can efficiently update one or more columns on a list of models. For example:
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)
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