返回介绍

Legacy Query Interface

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

Warning

The query interface is considered legacy in SQLAlchemy. Prefer using session.execute(select(...)) instead.

Flask-SQLAlchemy adds a query object to each model. This can be used to query instances of a given model. User.query is a shortcut for db.session.query(User).

# get the user with id 5
user = User.query.get(5)

# get a user by username
user = User.query.filter_by(username=username).one()

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.

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

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

  • Query.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/<username>")
def show_user(username):
    user = User.query.filter_by(username=username).one_or_404()
    return render_template("show_user.html", user=user)

You can add a custom message to the 404 error:

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

Pagination

If you have a lot of results, you may only want to show a certain number at a time, allowing the user to click next and previous links to see pages of data.

Call paginate() on a query to get a Pagination object. See Paging Query Results for more information about the pagination object.

During a request, this will take page and per_page arguments from the query string request.args. Pass max_per_page to prevent users from requesting too many results on a single page. If not given, the default values will be page 1 with 20 items per page.

page = User.query.order_by(User.join_date).paginate()
return render_template("user/list.html", page=page)

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

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

发布评论

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