Search code examples
pythonjsonpeewee

Get full result back from PeeWee query (for conversion to JSON)


I am trying to render a PeeWee query result as JSON using the following code:

@app.route('/')
def index():
    c = Category.select().order_by(Category.name).get()
    return jsonify(model_to_dict(c))

Doing this I only get one row back from the query. I'm pretty sure the issue is my use of get(), which the docs clearly say only returns one row. What do I use in place of get() to fetch the entire results back?

This question below pointed me in the right direction, but is is also using get()

Peewee model to JSON


Solution

  • What do I use in place of get() to fetch the entire results back?

    Modify your code to be:

    query = Category.select().order_by(Category.name)
    return jsonify({'rows':[model_to_dict(c) for c in query]})
    

    Alternatively, you could do:

    query = Category.select().order_by(Category.name).dicts()
    return jsonify({'rows':list(query)})