@@ -4,9 +4,11 @@ Performing raw SQL queries
44
55.. currentmodule:: django.db.models
66
7- Django gives you two ways of performing raw SQL queries: you can use
8- :meth:`Manager.raw` to `perform raw queries and return model instances`__, or
9- you can avoid the model layer entirely and `execute custom SQL directly`__.
7+ Django gives you three ways of performing raw SQL queries: you can embed raw
8+ SQL fragments into ORM queries using
9+ :class:`~django.db.models.expressions.RawSQL` (see :ref:`raw-sql-fragments`),
10+ use :meth:`Manager.raw` to `perform raw queries and return model instances`__,
11+ or avoid the model layer entirely and `execute custom SQL directly`__.
1012
1113__ `performing raw queries`_
1214__ `executing custom SQL directly`_
@@ -34,6 +36,19 @@ __ `executing custom SQL directly`_
3436 Please read more about :ref:`SQL injection protection
3537 <sql-injection-protection>`.
3638
39+ .. _raw-sql-fragments:
40+
41+ Raw SQL fragments
42+ =================
43+
44+ In some cases, you may need to embed raw SQL fragments directly into ORM
45+ queries — for example, in :meth:`~django.db.models.query.QuerySet.annotate` or
46+ :meth:`~django.db.models.query.QuerySet.filter` calls. Use :ref:`Func()
47+ expressions <func-expressions>` for calling database functions across
48+ backends, or
49+ :class:`~django.db.models.expressions.RawSQL` for arbitrary parameterized SQL
50+ fragments.
51+
3752.. _executing-raw-queries:
3853
3954Performing raw queries
@@ -195,28 +210,6 @@ must always be included in a raw query. A
195210:class:`~django.core.exceptions.FieldDoesNotExist` exception will be raised if
196211you forget to include the primary key.
197212
198- Adding annotations
199- ------------------
200-
201- You can also execute queries containing fields that aren't defined on the
202- model. For example, we could use `PostgreSQL's age() function`__ to get a list
203- of people with their ages calculated by the database:
204-
205- .. code-block:: pycon
206-
207- >>> people = Person.objects.raw("SELECT *, age(birth_date) AS age FROM myapp_person")
208- >>> for p in people:
209- ... print("%s is %s." % (p.first_name, p.age))
210- ...
211- John is 37.
212- Jane is 42.
213- ...
214-
215- You can often avoid using raw SQL to compute annotations by instead using a
216- :ref:`Func() expression <func-expressions>`.
217-
218- __ https://www.postgresql.org/docs/current/functions-datetime.html
219-
220213Passing parameters into ``raw()``
221214---------------------------------
222215
0 commit comments