diff options
Diffstat (limited to 'docs/topics/db/sql.txt')
| -rw-r--r-- | docs/topics/db/sql.txt | 43 |
1 files changed, 18 insertions, 25 deletions
diff --git a/docs/topics/db/sql.txt b/docs/topics/db/sql.txt index bd34df8bb7..da26f43347 100644 --- a/docs/topics/db/sql.txt +++ b/docs/topics/db/sql.txt @@ -4,9 +4,11 @@ Performing raw SQL queries .. currentmodule:: django.db.models -Django gives you two ways of performing raw SQL queries: you can use -:meth:`Manager.raw` to `perform raw queries and return model instances`__, or -you can avoid the model layer entirely and `execute custom SQL directly`__. +Django gives you three ways of performing raw SQL queries: you can embed raw +SQL fragments into ORM queries using +:class:`~django.db.models.expressions.RawSQL` (see :ref:`raw-sql-fragments`), +use :meth:`Manager.raw` to `perform raw queries and return model instances`__, +or avoid the model layer entirely and `execute custom SQL directly`__. __ `performing raw queries`_ __ `executing custom SQL directly`_ @@ -34,6 +36,19 @@ __ `executing custom SQL directly`_ Please read more about :ref:`SQL injection protection <sql-injection-protection>`. +.. _raw-sql-fragments: + +Raw SQL fragments +================= + +In some cases, you may need to embed raw SQL fragments directly into ORM +queries — for example, in :meth:`~django.db.models.query.QuerySet.annotate` or +:meth:`~django.db.models.query.QuerySet.filter` calls. Use :ref:`Func() +expressions <func-expressions>` for calling database functions across +backends, or +:class:`~django.db.models.expressions.RawSQL` for arbitrary parameterized SQL +fragments. + .. _executing-raw-queries: Performing raw queries @@ -195,28 +210,6 @@ must always be included in a raw query. A :class:`~django.core.exceptions.FieldDoesNotExist` exception will be raised if you forget to include the primary key. -Adding annotations ------------------- - -You can also execute queries containing fields that aren't defined on the -model. For example, we could use `PostgreSQL's age() function`__ to get a list -of people with their ages calculated by the database: - -.. code-block:: pycon - - >>> people = Person.objects.raw("SELECT *, age(birth_date) AS age FROM myapp_person") - >>> for p in people: - ... print("%s is %s." % (p.first_name, p.age)) - ... - John is 37. - Jane is 42. - ... - -You can often avoid using raw SQL to compute annotations by instead using a -:ref:`Func() expression <func-expressions>`. - -__ https://www.postgresql.org/docs/current/functions-datetime.html - Passing parameters into ``raw()`` --------------------------------- |
