使用 SQLAlchemy 和 Flask 时如何优化更新记录

发布于 2025-01-08 00:03:46 字数 1190 浏览 0 评论 0原文

我将 SQLAlchemy 与 Flask 和 Flask-SQLAlchemy 扩展一起使用。我困惑的是如何优化记录的更新。作为概念证明,我编写了以下端点:

@bp.route('/books', methods=['GET', 'PUT'], endpoint="books_index")
@bp.route('/books/<book_id>', methods=['GET', 'POST'], endpoint="books_show")
def books_index(book_id=None):
    book = Book.query.get_or_404(book_id) if book_id else Book()
    form = Book.model_form(request.form, book if book_id else None)
    verb = "updated" if book_id else "created"

    if form.validate_on_submit():
        form.populate_obj(book)
        db.session.add(book)
        db.session.commit()
        flash('Book %s successfully' % verb, 'info')

    return dict(
        books=[] if book_id else Book.query.all(), 
        book=book, 
        form=form
    )

一切都按照我想要的方式工作,但是在更新现有图书记录时,SQLAlchemy 运行三个查询,它们是:

  1. SELECT book.id AS book_id, book.title AS book_title FROM book WHERE书.id = ?
  2. 更新书集标题=?哪里的书.id = ?
  3. SELECT book.id AS book_id, book.title AS book_title FROM book WHERE book.id = ?

我理解为什么 SQLAlchemy 会进行所有三个查询,但仅仅更新一条记录似乎有点过分了。有没有办法优化这里发生的查询量?

(请注意,我在端点上进行了一些包装,以根据约定渲染模板,这就是您看不到 render_template 的原因)

I'm using SQLAlchemy with Flask and the Flask-SQLAlchemy extension. What I'm confused about is how to optimize the updating of a record. As a proof of concept I wrote the following endpoints:

@bp.route('/books', methods=['GET', 'PUT'], endpoint="books_index")
@bp.route('/books/<book_id>', methods=['GET', 'POST'], endpoint="books_show")
def books_index(book_id=None):
    book = Book.query.get_or_404(book_id) if book_id else Book()
    form = Book.model_form(request.form, book if book_id else None)
    verb = "updated" if book_id else "created"

    if form.validate_on_submit():
        form.populate_obj(book)
        db.session.add(book)
        db.session.commit()
        flash('Book %s successfully' % verb, 'info')

    return dict(
        books=[] if book_id else Book.query.all(), 
        book=book, 
        form=form
    )

Everything works as I want it to, but when updating an existing book record, SQLAlchemy runs three queries, they are:

  1. SELECT book.id AS book_id, book.title AS book_title FROM book WHERE book.id = ?
  2. UPDATE book SET title=? WHERE book.id = ?
  3. SELECT book.id AS book_id, book.title AS book_title FROM book WHERE book.id = ?

I understand why SQLAlchemy makes all three queries, but it seems a bit excessive for simply updating one record. Is there a way to optimize the amount of queries happening here?

(as a note, I've got some wrapping on the endpoints to render templates based on a convention which is why you don't see render_template)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文