3

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

Community
  • 1
  • 1
rp.
  • 17,483
  • 12
  • 63
  • 79
  • 1
    I'm pretty sure the answer is that the query needs to be iterated to fetch each row; and that get() is shorthand for fetching the first row. I was thinking that there might be an alternative to get() that didn't require the explicit iteration. I don't think there is. Right? – rp. Feb 05 '16 at 16:46

1 Answers1

13

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)})
rp.
  • 17,483
  • 12
  • 63
  • 79
coleifer
  • 24,887
  • 6
  • 60
  • 75
  • Had to modify jsonify's return value to be a dictionary. See this q/a http://stackoverflow.com/questions/12435297/how-do-i-jsonify-a-list-in-flask. Thanks, Charlie, you got me moving foward. – rp. Feb 06 '16 at 04:58
  • Thank you. I search for this exact problem, and it take me a while to get to your answer. Work like charm now. – Thang Nguyen Mar 14 '17 at 09:39