To my knowledge, a direct equivalent does not exist in peewee, though there is an all
method in the Dataset
extension, documented here. You can do this pretty easily using a list comprehension:
authors = [author for author in Author.select()]
Or even just authors = list(Author)
. However, if you're trying to return these as JSON, it won't work because your list of authors is populated by instances of Author
and Flask's JSONEncoder
will not work with this type out of the box. You can get around this by using peewee's dicts()
method:
authors = [author for author in Author.select().dicts()]
The full example would look like this:
@app.route('/authors')
def get_authors():
authors = [author for author in Author.select().dicts()]
return jsonify(authors)
Instead of serializing using dicts
I often use marshmallow
. For example you create an author_schema
like so:
from marshmallow import Schema, fields
class AuthorSchema(Schema):
id = fields.Integer(dump_only=True)
first = fields.String()
last = fields.String()
author_schema = AuthorSchema()
and use it like so (not showing imports):
@app.route('/authors')
def get_authors():
authors = author_schema(Author, many=True)
return jsonify(authors)