有没有办法在 peewee 中 query.all() ?

T1b*_*1us 7 python orm sqlalchemy peewee

我需要将所有数据从 SQL 表传输到 html 页面。在 SQLAlchemy 中我会做这样的事情:

class Author(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    first = db.Column(db.String(80))
    last = db.Column(db.String(80))


@app.route('/authors')
def get_authors():
    authors = Author.query.all()
    # Serialize the queryset
    result = authors_schema.dump(authors)
    return jsonify({'authors': result.data})
Run Code Online (Sandbox Code Playgroud)

有没有类似authors = Author.query.all()peewee的东西?

Rad*_*adu 7

据我所知,peewee 中不存在直接等效的方法,尽管扩展all中有一个方法Dataset,记录在此处。您可以使用列表理解轻松完成此操作:

authors = [author for author in Author.select()]
Run Code Online (Sandbox Code Playgroud)

或者甚至只是authors = list(Author)。但是,如果您尝试将它们作为 JSON 返回,它将不起作用,因为您的作者列表是由 的实例填充的,Author并且 FlaskJSONEncoder无法直接使用这种类型。您可以使用 peewee 的方法来解决这个问题dicts()

authors = [author for author in Author.select().dicts()]
Run Code Online (Sandbox Code Playgroud)

完整的示例如下所示:

@app.route('/authors')
def get_authors():
    authors = [author for author in Author.select().dicts()]
    return jsonify(authors)
Run Code Online (Sandbox Code Playgroud)

dicts我经常使用marshmallow. 例如,您创建一个author_schema像这样的:

from marshmallow import Schema, fields

class AuthorSchema(Schema):
    id = fields.Integer(dump_only=True)
    first = fields.String()
    last = fields.String()

author_schema = AuthorSchema()
Run Code Online (Sandbox Code Playgroud)

并像这样使用它(不显示导入):

@app.route('/authors')
def get_authors():
    authors = author_schema(Author, many=True)
    return jsonify(authors)
Run Code Online (Sandbox Code Playgroud)


T1b*_*1us 4

所以我做这个。

@app.route('/authors')
def get_authors():
    authors = Author.select()
    return render_template('aurhors.html', authors=authors)
Run Code Online (Sandbox Code Playgroud)

在 html 中是这样的。

 {% for a in authors %}
 <p>{{a.author_name}}</p>
 {% endfor %}
Run Code Online (Sandbox Code Playgroud)

我刚刚开始学习Python,所以感谢您的帮助。