2

我将 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 book.id = ?
  2. 更新书集标题=?在哪里 book.id = ?
  3. SELECT book.id AS book_id, book.title AS book_title FROM book WHERE book.id = ?

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

(作为说明,我在端点上进行了一些包装,以根据约定呈现模板,这就是您看不到的原因render_template

4

0 回答 0