使用 SQLAlchemy 和 Flask 时如何优化更新记录
我将 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 运行三个查询,它们是:
- SELECT book.id AS book_id, book.title AS book_title FROM book WHERE书.id = ?
- 更新书集标题=?哪里的书.id = ?
- 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:
- SELECT book.id AS book_id, book.title AS book_title FROM book WHERE book.id = ?
- UPDATE book SET title=? WHERE book.id = ?
- 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论