pythonpython-2.7peewee

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)

Solution

  • 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)