| 1 |
:orphan: |
| 2 |
|
| 3 |
Legacy Query Interface |
| 4 |
====================== |
| 5 |
|
| 6 |
.. warning:: |
| 7 |
The query interface is considered legacy in SQLAlchemy. Prefer using |
| 8 |
``session.execute(select(...))`` instead. |
| 9 |
|
| 10 |
Flask-SQLAlchemy adds a ``query`` object to each model. This can be used to query |
| 11 |
instances of a given model. ``User.query`` is a shortcut for ``db.session.query(User)``. |
| 12 |
|
| 13 |
.. code-block:: python |
| 14 |
|
| 15 |
# get the user with id 5 |
| 16 |
user = User.query.get(5) |
| 17 |
|
| 18 |
# get a user by username |
| 19 |
user = User.query.filter_by(username=username).one() |
| 20 |
|
| 21 |
|
| 22 |
Queries for Views |
| 23 |
----------------- |
| 24 |
|
| 25 |
If you write a Flask view function it's often useful to return a ``404 Not Found`` error |
| 26 |
for missing entries. Flask-SQLAlchemy provides some extra query methods. |
| 27 |
|
| 28 |
- :meth:`.Query.get_or_404` will raise a 404 if the row with the given id doesn't |
| 29 |
exist, otherwise it will return the instance. |
| 30 |
- :meth:`.Query.first_or_404` will raise a 404 if the query does not return any |
| 31 |
results, otherwise it will return the first result. |
| 32 |
- :meth:`.Query.one_or_404` will raise a 404 if the query does not return exactly one |
| 33 |
result, otherwise it will return the result. |
| 34 |
|
| 35 |
.. code-block:: python |
| 36 |
|
| 37 |
@app.route("/user/<username>") |
| 38 |
def show_user(username): |
| 39 |
user = User.query.filter_by(username=username).one_or_404() |
| 40 |
return render_template("show_user.html", user=user) |
| 41 |
|
| 42 |
You can add a custom message to the 404 error: |
| 43 |
|
| 44 |
.. code-block:: python |
| 45 |
|
| 46 |
user = User.query.filter_by(username=username).one_or_404( |
| 47 |
description=f"No user named '{username}'." |
| 48 |
) |
| 49 |
|
| 50 |
|
| 51 |
Pagination |
| 52 |
---------- |
| 53 |
|
| 54 |
If you have a lot of results, you may only want to show a certain number at a time, |
| 55 |
allowing the user to click next and previous links to see pages of data. |
| 56 |
|
| 57 |
Call :meth:`~.Query.paginate` on a query to get a :class:`.Pagination` object. See |
| 58 |
:doc:`/pagination` for more information about the pagination object. |
| 59 |
|
| 60 |
During a request, this will take ``page`` and ``per_page`` arguments from the query |
| 61 |
string ``request.args``. Pass ``max_per_page`` to prevent users from requesting too many |
| 62 |
results on a single page. If not given, the default values will be page 1 with 20 items |
| 63 |
per page. |
| 64 |
|
| 65 |
.. code-block:: python |
| 66 |
|
| 67 |
page = User.query.order_by(User.join_date).paginate() |
| 68 |
return render_template("user/list.html", page=page) |