Debian Codegraph @

docs/queries.rst

raw
1 Modifying and Querying Data
2 ===========================
3
4
5 Insert, Update, Delete
6 ----------------------
7
8 See SQLAlchemy's `ORM tutorial`_ and other SQLAlchemy documentation for more information
9 about modifying data with the ORM.
10
11 .. _ORM tutorial: https://docs.sqlalchemy.org/tutorial/orm_data_manipulation.html
12
13 To insert data, pass the model object to ``db.session.add()``:
14
15 .. code-block:: python
16
17 user = User()
18 db.session.add(user)
19 db.session.commit()
20
21 To update data, modify attributes on the model objects:
22
23 .. code-block:: python
24
25 user.verified = True
26 db.session.commit()
27
28 To delete data, pass the model object to ``db.session.delete()``:
29
30 .. code-block:: python
31
32 db.session.delete(user)
33 db.session.commit()
34
35 After modifying data, you must call ``db.session.commit()`` to commit the changes to
36 the database. Otherwise, they will be discarded at the end of the request.
37
38
39 Select
40 ------
41
42 See SQLAlchemy's `Querying Guide`_ and other SQLAlchemy documentation for more
43 information about querying data with the ORM.
44
45 .. _Querying Guide: https://docs.sqlalchemy.org/orm/queryguide.html
46
47 Queries are executed through ``db.session.execute()``. They can be constructed
48 using :func:`~sqlalchemy.sql.expression.select`. Executing a select returns a
49 :class:`~sqlalchemy.engine.Result` object that has many methods for working with the
50 returned rows.
51
52 .. code-block:: python
53
54 user = db.session.execute(db.select(User).filter_by(username=username)).scalar_one()
55
56 users = db.session.execute(db.select(User).order_by(User.username)).scalars()
57
58
59 Queries for Views
60 -----------------
61
62 If you write a Flask view function it's often useful to return a ``404 Not Found`` error
63 for missing entries. Flask-SQLAlchemy provides some extra query methods.
64
65 - :meth:`.SQLAlchemy.get_or_404` will raise a 404 if the row with the given id doesn't
66 exist, otherwise it will return the instance.
67 - :meth:`.SQLAlchemy.first_or_404` will raise a 404 if the query does not return any
68 results, otherwise it will return the first result.
69 - :meth:`.SQLAlchemy.one_or_404` will raise a 404 if the query does not return exactly
70 one result, otherwise it will return the result.
71
72 .. code-block:: python
73
74 @app.route("/user-by-id/<int:id>")
75 def user_by_id(id):
76 user = db.get_or_404(User, id)
77 return render_template("show_user.html", user=user)
78
79 @app.route("/user-by-username/<username>")
80 def user_by_username(username):
81 user = db.one_or_404(db.select(User).filter_by(username=username))
82 return render_template("show_user.html", user=user)
83
84 You can add a custom message to the 404 error:
85
86 .. code-block:: python
87
88 user = db.one_or_404(
89 db.select(User).filter_by(username=username),
90 description=f"No user named '{username}'."
91 )
92
93
94 Legacy Query Interface
95 ----------------------
96
97 You may see uses of ``Model.query`` or ``session.query`` to build queries. That query
98 interface is considered legacy in SQLAlchemy. Prefer using the
99 ``session.execute(select(...))`` instead.
100
101 See :doc:`legacy-query` for documentation.