返回介绍

Modifying and Querying Data

发布于 2023-05-20 01:15:15 字数 3636 浏览 0 评论 0 收藏 0

Insert, Update, Delete

See SQLAlchemy’s ORM tutorial and other SQLAlchemy documentation for more information about modifying data with the ORM.

To insert data, pass the model object to db.session.add():

user = User()
db.session.add(user)
db.session.commit()

To update data, modify attributes on the model objects:

user.verified = True
db.session.commit()

To delete data, pass the model object to db.session.delete():

db.session.delete(user)
db.session.commit()

After modifying data, you must call db.session.commit() to commit the changes to the database. Otherwise, they will be discarded at the end of the request.

Select

See SQLAlchemy’s Querying Guide and other SQLAlchemy documentation for more information about querying data with the ORM.

Queries are executed through db.session.execute(). They can be constructed using select(). Executing a select returns a Result object that has many methods for working with the returned rows.

user = db.session.execute(db.select(User).filter_by(username=username)).scalar_one()

users = db.session.execute(db.select(User).order_by(User.username)).scalars()

Queries for Views

If you write a Flask view function it’s often useful to return a 404 Not Found error for missing entries. Flask-SQLAlchemy provides some extra query methods.

  • SQLAlchemy.get_or_404() will raise a 404 if the row with the given id doesn’t exist, otherwise it will return the instance.

  • SQLAlchemy.first_or_404() will raise a 404 if the query does not return any results, otherwise it will return the first result.

  • SQLAlchemy.one_or_404() will raise a 404 if the query does not return exactly one result, otherwise it will return the result.

@app.route("/user-by-id/<int:id>")
def user_by_id(id):
    user = db.get_or_404(User, id)
    return render_template("show_user.html", user=user)

@app.route("/user-by-username/<username>")
def user_by_username(username):
    user = db.one_or_404(db.select(User).filter_by(username=username))
    return render_template("show_user.html", user=user)

You can add a custom message to the 404 error:

user = db.one_or_404(
    db.select(User).filter_by(username=username),
    description=f"No user named '{username}'."
)

Legacy Query Interface

You may see uses of Model.query or session.query to build queries. That query interface is considered legacy in SQLAlchemy. Prefer using the session.execute(select(...)) instead.

See Legacy Query Interface for documentation.

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

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

发布评论

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