Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get list of query results in Peewee

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)
like image 617
valanto Avatar asked Aug 04 '17 07:08

valanto


People also ask

How are queries constructed in peewee?

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.

Does Peewee cache the rows returned from a SELECT 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.

What are common table expressions (CTEs) in peewee?

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.

How can I efficiently update a list of models in peewee?

In addition, Peewee also offers Model.bulk_update (), which can efficiently update one or more columns on a list of models. For example:


1 Answers

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)
like image 159
wyattis Avatar answered Sep 27 '22 22:09

wyattis