expressions.txt 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315
  1. =================
  2. Query Expressions
  3. =================
  4. .. currentmodule:: django.db.models
  5. Query expressions describe a value or a computation that can be used as part of
  6. an update, create, filter, order by, annotation, or aggregate. When an
  7. expression outputs a boolean value, it may be used directly in filters. There
  8. are a number of built-in expressions (documented below) that can be used to
  9. help you write queries. Expressions can be combined, or in some cases nested,
  10. to form more complex computations.
  11. Supported arithmetic
  12. ====================
  13. Django supports negation, addition, subtraction, multiplication, division,
  14. modulo arithmetic, and the power operator on query expressions, using Python
  15. constants, variables, and even other expressions.
  16. Some examples
  17. =============
  18. .. code-block:: pycon
  19. >>> from django.db.models import Count, F, Value
  20. >>> from django.db.models.functions import Length, Upper
  21. >>> from django.db.models.lookups import GreaterThan
  22. # Find companies that have more employees than chairs.
  23. >>> Company.objects.filter(num_employees__gt=F("num_chairs"))
  24. # Find companies that have at least twice as many employees
  25. # as chairs. Both the querysets below are equivalent.
  26. >>> Company.objects.filter(num_employees__gt=F("num_chairs") * 2)
  27. >>> Company.objects.filter(num_employees__gt=F("num_chairs") + F("num_chairs"))
  28. # How many chairs are needed for each company to seat all employees?
  29. >>> company = (
  30. ... Company.objects.filter(num_employees__gt=F("num_chairs"))
  31. ... .annotate(chairs_needed=F("num_employees") - F("num_chairs"))
  32. ... .first()
  33. ... )
  34. >>> company.num_employees
  35. 120
  36. >>> company.num_chairs
  37. 50
  38. >>> company.chairs_needed
  39. 70
  40. # Create a new company using expressions.
  41. >>> company = Company.objects.create(name="Google", ticker=Upper(Value("goog")))
  42. # Be sure to refresh it if you need to access the field.
  43. >>> company.refresh_from_db()
  44. >>> company.ticker
  45. 'GOOG'
  46. # Annotate models with an aggregated value. Both forms
  47. # below are equivalent.
  48. Company.objects.annotate(num_products=Count('products'))
  49. Company.objects.annotate(num_products=Count(F('products')))
  50. # Aggregates can contain complex computations also
  51. Company.objects.annotate(num_offerings=Count(F('products') + F('services')))
  52. # Expressions can also be used in order_by(), either directly
  53. Company.objects.order_by(Length('name').asc())
  54. Company.objects.order_by(Length('name').desc())
  55. # or using the double underscore lookup syntax.
  56. from django.db.models import CharField
  57. from django.db.models.functions import Length
  58. CharField.register_lookup(Length)
  59. Company.objects.order_by('name__length')
  60. # Boolean expression can be used directly in filters.
  61. from django.db.models import Exists
  62. Company.objects.filter(
  63. Exists(Employee.objects.filter(company=OuterRef('pk'), salary__gt=10))
  64. )
  65. # Lookup expressions can also be used directly in filters
  66. Company.objects.filter(GreaterThan(F('num_employees'), F('num_chairs')))
  67. # or annotations.
  68. Company.objects.annotate(
  69. need_chairs=GreaterThan(F('num_employees'), F('num_chairs')),
  70. )
  71. Built-in Expressions
  72. ====================
  73. .. note::
  74. These expressions are defined in ``django.db.models.expressions`` and
  75. ``django.db.models.aggregates``, but for convenience they're available and
  76. usually imported from :mod:`django.db.models`.
  77. ``F()`` expressions
  78. -------------------
  79. .. class:: F
  80. An ``F()`` object represents the value of a model field, transformed value of a
  81. model field, or annotated column. It makes it possible to refer to model field
  82. values and perform database operations using them without actually having to
  83. pull them out of the database into Python memory.
  84. Instead, Django uses the ``F()`` object to generate an SQL expression that
  85. describes the required operation at the database level.
  86. Let's try this with an example. Normally, one might do something like this::
  87. # Tintin filed a news story!
  88. reporter = Reporters.objects.get(name="Tintin")
  89. reporter.stories_filed += 1
  90. reporter.save()
  91. Here, we have pulled the value of ``reporter.stories_filed`` from the database
  92. into memory and manipulated it using familiar Python operators, and then saved
  93. the object back to the database. But instead we could also have done::
  94. from django.db.models import F
  95. reporter = Reporters.objects.get(name="Tintin")
  96. reporter.stories_filed = F("stories_filed") + 1
  97. reporter.save()
  98. Although ``reporter.stories_filed = F('stories_filed') + 1`` looks like a
  99. normal Python assignment of value to an instance attribute, in fact it's an SQL
  100. construct describing an operation on the database.
  101. When Django encounters an instance of ``F()``, it overrides the standard Python
  102. operators to create an encapsulated SQL expression; in this case, one which
  103. instructs the database to increment the database field represented by
  104. ``reporter.stories_filed``.
  105. Whatever value is or was on ``reporter.stories_filed``, Python never gets to
  106. know about it - it is dealt with entirely by the database. All Python does,
  107. through Django's ``F()`` class, is create the SQL syntax to refer to the field
  108. and describe the operation.
  109. To access the new value saved this way, the object must be reloaded::
  110. reporter = Reporters.objects.get(pk=reporter.pk)
  111. # Or, more succinctly:
  112. reporter.refresh_from_db()
  113. As well as being used in operations on single instances as above, ``F()`` can
  114. be used on ``QuerySets`` of object instances, with ``update()``. This reduces
  115. the two queries we were using above - the ``get()`` and the
  116. :meth:`~Model.save()` - to just one::
  117. reporter = Reporters.objects.filter(name="Tintin")
  118. reporter.update(stories_filed=F("stories_filed") + 1)
  119. We can also use :meth:`~django.db.models.query.QuerySet.update()` to increment
  120. the field value on multiple objects - which could be very much faster than
  121. pulling them all into Python from the database, looping over them, incrementing
  122. the field value of each one, and saving each one back to the database::
  123. Reporter.objects.update(stories_filed=F("stories_filed") + 1)
  124. ``F()`` therefore can offer performance advantages by:
  125. * getting the database, rather than Python, to do work
  126. * reducing the number of queries some operations require
  127. .. _avoiding-race-conditions-using-f:
  128. Avoiding race conditions using ``F()``
  129. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  130. Another useful benefit of ``F()`` is that having the database - rather than
  131. Python - update a field's value avoids a *race condition*.
  132. If two Python threads execute the code in the first example above, one thread
  133. could retrieve, increment, and save a field's value after the other has
  134. retrieved it from the database. The value that the second thread saves will be
  135. based on the original value; the work of the first thread will be lost.
  136. If the database is responsible for updating the field, the process is more
  137. robust: it will only ever update the field based on the value of the field in
  138. the database when the :meth:`~Model.save()` or ``update()`` is executed, rather
  139. than based on its value when the instance was retrieved.
  140. ``F()`` assignments persist after ``Model.save()``
  141. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  142. ``F()`` objects assigned to model fields persist after saving the model
  143. instance and will be applied on each :meth:`~Model.save()`. For example::
  144. reporter = Reporters.objects.get(name="Tintin")
  145. reporter.stories_filed = F("stories_filed") + 1
  146. reporter.save()
  147. reporter.name = "Tintin Jr."
  148. reporter.save()
  149. ``stories_filed`` will be updated twice in this case. If it's initially ``1``,
  150. the final value will be ``3``. This persistence can be avoided by reloading the
  151. model object after saving it, for example, by using
  152. :meth:`~Model.refresh_from_db()`.
  153. Using ``F()`` in filters
  154. ~~~~~~~~~~~~~~~~~~~~~~~~
  155. ``F()`` is also very useful in ``QuerySet`` filters, where they make it
  156. possible to filter a set of objects against criteria based on their field
  157. values, rather than on Python values.
  158. This is documented in :ref:`using F() expressions in queries
  159. <using-f-expressions-in-filters>`.
  160. .. _using-f-with-annotations:
  161. Using ``F()`` with annotations
  162. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  163. ``F()`` can be used to create dynamic fields on your models by combining
  164. different fields with arithmetic::
  165. company = Company.objects.annotate(chairs_needed=F("num_employees") - F("num_chairs"))
  166. If the fields that you're combining are of different types you'll need
  167. to tell Django what kind of field will be returned. Since ``F()`` does not
  168. directly support ``output_field`` you will need to wrap the expression with
  169. :class:`ExpressionWrapper`::
  170. from django.db.models import DateTimeField, ExpressionWrapper, F
  171. Ticket.objects.annotate(
  172. expires=ExpressionWrapper(
  173. F("active_at") + F("duration"), output_field=DateTimeField()
  174. )
  175. )
  176. When referencing relational fields such as ``ForeignKey``, ``F()`` returns the
  177. primary key value rather than a model instance:
  178. .. code-block:: pycon
  179. >> car = Company.objects.annotate(built_by=F('manufacturer'))[0]
  180. >> car.manufacturer
  181. <Manufacturer: Toyota>
  182. >> car.built_by
  183. 3
  184. .. _using-f-to-sort-null-values:
  185. Using ``F()`` to sort null values
  186. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  187. Use ``F()`` and the ``nulls_first`` or ``nulls_last`` keyword argument to
  188. :meth:`.Expression.asc` or :meth:`~.Expression.desc` to control the ordering of
  189. a field's null values. By default, the ordering depends on your database.
  190. For example, to sort companies that haven't been contacted (``last_contacted``
  191. is null) after companies that have been contacted::
  192. from django.db.models import F
  193. Company.objects.order_by(F("last_contacted").desc(nulls_last=True))
  194. Using ``F()`` with logical operations
  195. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  196. .. versionadded:: 4.2
  197. ``F()`` expressions that output ``BooleanField`` can be logically negated with
  198. the inversion operator ``~F()``. For example, to swap the activation status of
  199. companies::
  200. from django.db.models import F
  201. Company.objects.update(is_active=~F("is_active"))
  202. .. _func-expressions:
  203. ``Func()`` expressions
  204. ----------------------
  205. ``Func()`` expressions are the base type of all expressions that involve
  206. database functions like ``COALESCE`` and ``LOWER``, or aggregates like ``SUM``.
  207. They can be used directly::
  208. from django.db.models import F, Func
  209. queryset.annotate(field_lower=Func(F("field"), function="LOWER"))
  210. or they can be used to build a library of database functions::
  211. class Lower(Func):
  212. function = "LOWER"
  213. queryset.annotate(field_lower=Lower("field"))
  214. But both cases will result in a queryset where each model is annotated with an
  215. extra attribute ``field_lower`` produced, roughly, from the following SQL:
  216. .. code-block:: sql
  217. SELECT
  218. ...
  219. LOWER("db_table"."field") as "field_lower"
  220. See :doc:`database-functions` for a list of built-in database functions.
  221. The ``Func`` API is as follows:
  222. .. class:: Func(*expressions, **extra)
  223. .. attribute:: function
  224. A class attribute describing the function that will be generated.
  225. Specifically, the ``function`` will be interpolated as the ``function``
  226. placeholder within :attr:`template`. Defaults to ``None``.
  227. .. attribute:: template
  228. A class attribute, as a format string, that describes the SQL that is
  229. generated for this function. Defaults to
  230. ``'%(function)s(%(expressions)s)'``.
  231. If you're constructing SQL like ``strftime('%W', 'date')`` and need a
  232. literal ``%`` character in the query, quadruple it (``%%%%``) in the
  233. ``template`` attribute because the string is interpolated twice: once
  234. during the template interpolation in ``as_sql()`` and once in the SQL
  235. interpolation with the query parameters in the database cursor.
  236. .. attribute:: arg_joiner
  237. A class attribute that denotes the character used to join the list of
  238. ``expressions`` together. Defaults to ``', '``.
  239. .. attribute:: arity
  240. A class attribute that denotes the number of arguments the function
  241. accepts. If this attribute is set and the function is called with a
  242. different number of expressions, ``TypeError`` will be raised. Defaults
  243. to ``None``.
  244. .. method:: as_sql(compiler, connection, function=None, template=None, arg_joiner=None, **extra_context)
  245. Generates the SQL fragment for the database function. Returns a tuple
  246. ``(sql, params)``, where ``sql`` is the SQL string, and ``params`` is
  247. the list or tuple of query parameters.
  248. The ``as_vendor()`` methods should use the ``function``, ``template``,
  249. ``arg_joiner``, and any other ``**extra_context`` parameters to
  250. customize the SQL as needed. For example:
  251. .. code-block:: python
  252. :caption: ``django/db/models/functions.py``
  253. class ConcatPair(Func):
  254. ...
  255. function = "CONCAT"
  256. ...
  257. def as_mysql(self, compiler, connection, **extra_context):
  258. return super().as_sql(
  259. compiler,
  260. connection,
  261. function="CONCAT_WS",
  262. template="%(function)s('', %(expressions)s)",
  263. **extra_context
  264. )
  265. To avoid an SQL injection vulnerability, ``extra_context`` :ref:`must
  266. not contain untrusted user input <avoiding-sql-injection-in-query-expressions>`
  267. as these values are interpolated into the SQL string rather than passed
  268. as query parameters, where the database driver would escape them.
  269. The ``*expressions`` argument is a list of positional expressions that the
  270. function will be applied to. The expressions will be converted to strings,
  271. joined together with ``arg_joiner``, and then interpolated into the ``template``
  272. as the ``expressions`` placeholder.
  273. Positional arguments can be expressions or Python values. Strings are
  274. assumed to be column references and will be wrapped in ``F()`` expressions
  275. while other values will be wrapped in ``Value()`` expressions.
  276. The ``**extra`` kwargs are ``key=value`` pairs that can be interpolated
  277. into the ``template`` attribute. To avoid an SQL injection vulnerability,
  278. ``extra`` :ref:`must not contain untrusted user input
  279. <avoiding-sql-injection-in-query-expressions>` as these values are interpolated
  280. into the SQL string rather than passed as query parameters, where the database
  281. driver would escape them.
  282. The ``function``, ``template``, and ``arg_joiner`` keywords can be used to
  283. replace the attributes of the same name without having to define your own
  284. class. ``output_field`` can be used to define the expected return type.
  285. ``Aggregate()`` expressions
  286. ---------------------------
  287. An aggregate expression is a special case of a :ref:`Func() expression
  288. <func-expressions>` that informs the query that a ``GROUP BY`` clause
  289. is required. All of the :ref:`aggregate functions <aggregation-functions>`,
  290. like ``Sum()`` and ``Count()``, inherit from ``Aggregate()``.
  291. Since ``Aggregate``\s are expressions and wrap expressions, you can represent
  292. some complex computations::
  293. from django.db.models import Count
  294. Company.objects.annotate(
  295. managers_required=(Count("num_employees") / 4) + Count("num_managers")
  296. )
  297. The ``Aggregate`` API is as follows:
  298. .. class:: Aggregate(*expressions, output_field=None, distinct=False, filter=None, default=None, **extra)
  299. .. attribute:: template
  300. A class attribute, as a format string, that describes the SQL that is
  301. generated for this aggregate. Defaults to
  302. ``'%(function)s(%(distinct)s%(expressions)s)'``.
  303. .. attribute:: function
  304. A class attribute describing the aggregate function that will be
  305. generated. Specifically, the ``function`` will be interpolated as the
  306. ``function`` placeholder within :attr:`template`. Defaults to ``None``.
  307. .. attribute:: window_compatible
  308. Defaults to ``True`` since most aggregate functions can be used as the
  309. source expression in :class:`~django.db.models.expressions.Window`.
  310. .. attribute:: allow_distinct
  311. A class attribute determining whether or not this aggregate function
  312. allows passing a ``distinct`` keyword argument. If set to ``False``
  313. (default), ``TypeError`` is raised if ``distinct=True`` is passed.
  314. .. attribute:: empty_result_set_value
  315. Defaults to ``None`` since most aggregate functions result in ``NULL``
  316. when applied to an empty result set.
  317. The ``expressions`` positional arguments can include expressions, transforms of
  318. the model field, or the names of model fields. They will be converted to a
  319. string and used as the ``expressions`` placeholder within the ``template``.
  320. The ``output_field`` argument requires a model field instance, like
  321. ``IntegerField()`` or ``BooleanField()``, into which Django will load the value
  322. after it's retrieved from the database. Usually no arguments are needed when
  323. instantiating the model field as any arguments relating to data validation
  324. (``max_length``, ``max_digits``, etc.) will not be enforced on the expression's
  325. output value.
  326. Note that ``output_field`` is only required when Django is unable to determine
  327. what field type the result should be. Complex expressions that mix field types
  328. should define the desired ``output_field``. For example, adding an
  329. ``IntegerField()`` and a ``FloatField()`` together should probably have
  330. ``output_field=FloatField()`` defined.
  331. The ``distinct`` argument determines whether or not the aggregate function
  332. should be invoked for each distinct value of ``expressions`` (or set of
  333. values, for multiple ``expressions``). The argument is only supported on
  334. aggregates that have :attr:`~Aggregate.allow_distinct` set to ``True``.
  335. The ``filter`` argument takes a :class:`Q object <django.db.models.Q>` that's
  336. used to filter the rows that are aggregated. See :ref:`conditional-aggregation`
  337. and :ref:`filtering-on-annotations` for example usage.
  338. The ``default`` argument takes a value that will be passed along with the
  339. aggregate to :class:`~django.db.models.functions.Coalesce`. This is useful for
  340. specifying a value to be returned other than ``None`` when the queryset (or
  341. grouping) contains no entries.
  342. The ``**extra`` kwargs are ``key=value`` pairs that can be interpolated
  343. into the ``template`` attribute.
  344. Creating your own Aggregate Functions
  345. -------------------------------------
  346. You can create your own aggregate functions, too. At a minimum, you need to
  347. define ``function``, but you can also completely customize the SQL that is
  348. generated. Here's a brief example::
  349. from django.db.models import Aggregate
  350. class Sum(Aggregate):
  351. # Supports SUM(ALL field).
  352. function = "SUM"
  353. template = "%(function)s(%(all_values)s%(expressions)s)"
  354. allow_distinct = False
  355. def __init__(self, expression, all_values=False, **extra):
  356. super().__init__(expression, all_values="ALL " if all_values else "", **extra)
  357. ``Value()`` expressions
  358. -----------------------
  359. .. class:: Value(value, output_field=None)
  360. A ``Value()`` object represents the smallest possible component of an
  361. expression: a simple value. When you need to represent the value of an integer,
  362. boolean, or string within an expression, you can wrap that value within a
  363. ``Value()``.
  364. You will rarely need to use ``Value()`` directly. When you write the expression
  365. ``F('field') + 1``, Django implicitly wraps the ``1`` in a ``Value()``,
  366. allowing simple values to be used in more complex expressions. You will need to
  367. use ``Value()`` when you want to pass a string to an expression. Most
  368. expressions interpret a string argument as the name of a field, like
  369. ``Lower('name')``.
  370. The ``value`` argument describes the value to be included in the expression,
  371. such as ``1``, ``True``, or ``None``. Django knows how to convert these Python
  372. values into their corresponding database type.
  373. The ``output_field`` argument should be a model field instance, like
  374. ``IntegerField()`` or ``BooleanField()``, into which Django will load the value
  375. after it's retrieved from the database. Usually no arguments are needed when
  376. instantiating the model field as any arguments relating to data validation
  377. (``max_length``, ``max_digits``, etc.) will not be enforced on the expression's
  378. output value. If no ``output_field`` is specified it will be tentatively
  379. inferred from the :py:class:`type` of the provided ``value``, if possible. For
  380. example, passing an instance of :py:class:`datetime.datetime` as ``value``
  381. would default ``output_field`` to :class:`~django.db.models.DateTimeField`.
  382. ``ExpressionWrapper()`` expressions
  383. -----------------------------------
  384. .. class:: ExpressionWrapper(expression, output_field)
  385. ``ExpressionWrapper`` surrounds another expression and provides access to
  386. properties, such as ``output_field``, that may not be available on other
  387. expressions. ``ExpressionWrapper`` is necessary when using arithmetic on
  388. ``F()`` expressions with different types as described in
  389. :ref:`using-f-with-annotations`.
  390. Conditional expressions
  391. -----------------------
  392. Conditional expressions allow you to use :keyword:`if` ... :keyword:`elif` ...
  393. :keyword:`else` logic in queries. Django natively supports SQL ``CASE``
  394. expressions. For more details see :doc:`conditional-expressions`.
  395. ``Subquery()`` expressions
  396. --------------------------
  397. .. class:: Subquery(queryset, output_field=None)
  398. You can add an explicit subquery to a ``QuerySet`` using the ``Subquery``
  399. expression.
  400. For example, to annotate each post with the email address of the author of the
  401. newest comment on that post:
  402. .. code-block:: pycon
  403. >>> from django.db.models import OuterRef, Subquery
  404. >>> newest = Comment.objects.filter(post=OuterRef("pk")).order_by("-created_at")
  405. >>> Post.objects.annotate(newest_commenter_email=Subquery(newest.values("email")[:1]))
  406. On PostgreSQL, the SQL looks like:
  407. .. code-block:: sql
  408. SELECT "post"."id", (
  409. SELECT U0."email"
  410. FROM "comment" U0
  411. WHERE U0."post_id" = ("post"."id")
  412. ORDER BY U0."created_at" DESC LIMIT 1
  413. ) AS "newest_commenter_email" FROM "post"
  414. .. note::
  415. The examples in this section are designed to show how to force
  416. Django to execute a subquery. In some cases it may be possible to
  417. write an equivalent queryset that performs the same task more
  418. clearly or efficiently.
  419. Referencing columns from the outer queryset
  420. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  421. .. class:: OuterRef(field)
  422. Use ``OuterRef`` when a queryset in a ``Subquery`` needs to refer to a field
  423. from the outer query or its transform. It acts like an :class:`F` expression
  424. except that the check to see if it refers to a valid field isn't made until the
  425. outer queryset is resolved.
  426. Instances of ``OuterRef`` may be used in conjunction with nested instances
  427. of ``Subquery`` to refer to a containing queryset that isn't the immediate
  428. parent. For example, this queryset would need to be within a nested pair of
  429. ``Subquery`` instances to resolve correctly:
  430. .. code-block:: pycon
  431. >>> Book.objects.filter(author=OuterRef(OuterRef("pk")))
  432. Limiting a subquery to a single column
  433. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  434. There are times when a single column must be returned from a ``Subquery``, for
  435. instance, to use a ``Subquery`` as the target of an ``__in`` lookup. To return
  436. all comments for posts published within the last day:
  437. .. code-block:: pycon
  438. >>> from datetime import timedelta
  439. >>> from django.utils import timezone
  440. >>> one_day_ago = timezone.now() - timedelta(days=1)
  441. >>> posts = Post.objects.filter(published_at__gte=one_day_ago)
  442. >>> Comment.objects.filter(post__in=Subquery(posts.values("pk")))
  443. In this case, the subquery must use :meth:`~.QuerySet.values`
  444. to return only a single column: the primary key of the post.
  445. Limiting the subquery to a single row
  446. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  447. To prevent a subquery from returning multiple rows, a slice (``[:1]``) of the
  448. queryset is used:
  449. .. code-block:: pycon
  450. >>> subquery = Subquery(newest.values("email")[:1])
  451. >>> Post.objects.annotate(newest_commenter_email=subquery)
  452. In this case, the subquery must only return a single column *and* a single
  453. row: the email address of the most recently created comment.
  454. (Using :meth:`~.QuerySet.get` instead of a slice would fail because the
  455. ``OuterRef`` cannot be resolved until the queryset is used within a
  456. ``Subquery``.)
  457. ``Exists()`` subqueries
  458. ~~~~~~~~~~~~~~~~~~~~~~~
  459. .. class:: Exists(queryset)
  460. ``Exists`` is a ``Subquery`` subclass that uses an SQL ``EXISTS`` statement. In
  461. many cases it will perform better than a subquery since the database is able to
  462. stop evaluation of the subquery when a first matching row is found.
  463. For example, to annotate each post with whether or not it has a comment from
  464. within the last day:
  465. .. code-block:: pycon
  466. >>> from django.db.models import Exists, OuterRef
  467. >>> from datetime import timedelta
  468. >>> from django.utils import timezone
  469. >>> one_day_ago = timezone.now() - timedelta(days=1)
  470. >>> recent_comments = Comment.objects.filter(
  471. ... post=OuterRef("pk"),
  472. ... created_at__gte=one_day_ago,
  473. ... )
  474. >>> Post.objects.annotate(recent_comment=Exists(recent_comments))
  475. On PostgreSQL, the SQL looks like:
  476. .. code-block:: sql
  477. SELECT "post"."id", "post"."published_at", EXISTS(
  478. SELECT (1) as "a"
  479. FROM "comment" U0
  480. WHERE (
  481. U0."created_at" >= YYYY-MM-DD HH:MM:SS AND
  482. U0."post_id" = "post"."id"
  483. )
  484. LIMIT 1
  485. ) AS "recent_comment" FROM "post"
  486. It's unnecessary to force ``Exists`` to refer to a single column, since the
  487. columns are discarded and a boolean result is returned. Similarly, since
  488. ordering is unimportant within an SQL ``EXISTS`` subquery and would only
  489. degrade performance, it's automatically removed.
  490. You can query using ``NOT EXISTS`` with ``~Exists()``.
  491. Filtering on a ``Subquery()`` or ``Exists()`` expressions
  492. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  493. ``Subquery()`` that returns a boolean value and ``Exists()`` may be used as a
  494. ``condition`` in :class:`~django.db.models.expressions.When` expressions, or to
  495. directly filter a queryset:
  496. .. code-block:: pycon
  497. >>> recent_comments = Comment.objects.filter(...) # From above
  498. >>> Post.objects.filter(Exists(recent_comments))
  499. This will ensure that the subquery will not be added to the ``SELECT`` columns,
  500. which may result in a better performance.
  501. Using aggregates within a ``Subquery`` expression
  502. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  503. Aggregates may be used within a ``Subquery``, but they require a specific
  504. combination of :meth:`~.QuerySet.filter`, :meth:`~.QuerySet.values`, and
  505. :meth:`~.QuerySet.annotate` to get the subquery grouping correct.
  506. Assuming both models have a ``length`` field, to find posts where the post
  507. length is greater than the total length of all combined comments:
  508. .. code-block:: pycon
  509. >>> from django.db.models import OuterRef, Subquery, Sum
  510. >>> comments = Comment.objects.filter(post=OuterRef("pk")).order_by().values("post")
  511. >>> total_comments = comments.annotate(total=Sum("length")).values("total")
  512. >>> Post.objects.filter(length__gt=Subquery(total_comments))
  513. The initial ``filter(...)`` limits the subquery to the relevant parameters.
  514. ``order_by()`` removes the default :attr:`~django.db.models.Options.ordering`
  515. (if any) on the ``Comment`` model. ``values('post')`` aggregates comments by
  516. ``Post``. Finally, ``annotate(...)`` performs the aggregation. The order in
  517. which these queryset methods are applied is important. In this case, since the
  518. subquery must be limited to a single column, ``values('total')`` is required.
  519. This is the only way to perform an aggregation within a ``Subquery``, as
  520. using :meth:`~.QuerySet.aggregate` attempts to evaluate the queryset (and if
  521. there is an ``OuterRef``, this will not be possible to resolve).
  522. Raw SQL expressions
  523. -------------------
  524. .. currentmodule:: django.db.models.expressions
  525. .. class:: RawSQL(sql, params, output_field=None)
  526. Sometimes database expressions can't easily express a complex ``WHERE`` clause.
  527. In these edge cases, use the ``RawSQL`` expression. For example:
  528. .. code-block:: pycon
  529. >>> from django.db.models.expressions import RawSQL
  530. >>> queryset.annotate(val=RawSQL("select col from sometable where othercol = %s", (param,)))
  531. These extra lookups may not be portable to different database engines (because
  532. you're explicitly writing SQL code) and violate the DRY principle, so you
  533. should avoid them if possible.
  534. ``RawSQL`` expressions can also be used as the target of ``__in`` filters:
  535. .. code-block:: pycon
  536. >>> queryset.filter(id__in=RawSQL("select id from sometable where col = %s", (param,)))
  537. .. warning::
  538. To protect against `SQL injection attacks
  539. <https://en.wikipedia.org/wiki/SQL_injection>`_, you must escape any
  540. parameters that the user can control by using ``params``. ``params`` is a
  541. required argument to force you to acknowledge that you're not interpolating
  542. your SQL with user-provided data.
  543. You also must not quote placeholders in the SQL string. This example is
  544. vulnerable to SQL injection because of the quotes around ``%s``:
  545. .. code-block:: pycon
  546. RawSQL("select col from sometable where othercol = '%s'") # unsafe!
  547. You can read more about how Django's :ref:`SQL injection protection
  548. <sql-injection-protection>` works.
  549. Window functions
  550. ----------------
  551. Window functions provide a way to apply functions on partitions. Unlike a
  552. normal aggregation function which computes a final result for each set defined
  553. by the group by, window functions operate on :ref:`frames <window-frames>` and
  554. partitions, and compute the result for each row.
  555. You can specify multiple windows in the same query which in Django ORM would be
  556. equivalent to including multiple expressions in a :doc:`QuerySet.annotate()
  557. </topics/db/aggregation>` call. The ORM doesn't make use of named windows,
  558. instead they are part of the selected columns.
  559. .. class:: Window(expression, partition_by=None, order_by=None, frame=None, output_field=None)
  560. .. attribute:: template
  561. Defaults to ``%(expression)s OVER (%(window)s)'``. If only the
  562. ``expression`` argument is provided, the window clause will be blank.
  563. The ``Window`` class is the main expression for an ``OVER`` clause.
  564. The ``expression`` argument is either a :ref:`window function
  565. <window-functions>`, an :ref:`aggregate function <aggregation-functions>`, or
  566. an expression that's compatible in a window clause.
  567. The ``partition_by`` argument accepts an expression or a sequence of
  568. expressions (column names should be wrapped in an ``F``-object) that control
  569. the partitioning of the rows. Partitioning narrows which rows are used to
  570. compute the result set.
  571. The ``output_field`` is specified either as an argument or by the expression.
  572. The ``order_by`` argument accepts an expression on which you can call
  573. :meth:`~django.db.models.Expression.asc` and
  574. :meth:`~django.db.models.Expression.desc`, a string of a field name (with an
  575. optional ``"-"`` prefix which indicates descending order), or a tuple or list
  576. of strings and/or expressions. The ordering controls the order in which the
  577. expression is applied. For example, if you sum over the rows in a partition,
  578. the first result is the value of the first row, the second is the sum of first
  579. and second row.
  580. The ``frame`` parameter specifies which other rows that should be used in the
  581. computation. See :ref:`window-frames` for details.
  582. For example, to annotate each movie with the average rating for the movies by
  583. the same studio in the same genre and release year:
  584. .. code-block:: pycon
  585. >>> from django.db.models import Avg, F, Window
  586. >>> Movie.objects.annotate(
  587. ... avg_rating=Window(
  588. ... expression=Avg("rating"),
  589. ... partition_by=[F("studio"), F("genre")],
  590. ... order_by="released__year",
  591. ... ),
  592. ... )
  593. This allows you to check if a movie is rated better or worse than its peers.
  594. You may want to apply multiple expressions over the same window, i.e., the
  595. same partition and frame. For example, you could modify the previous example
  596. to also include the best and worst rating in each movie's group (same studio,
  597. genre, and release year) by using three window functions in the same query. The
  598. partition and ordering from the previous example is extracted into a dictionary
  599. to reduce repetition:
  600. .. code-block:: pycon
  601. >>> from django.db.models import Avg, F, Max, Min, Window
  602. >>> window = {
  603. ... "partition_by": [F("studio"), F("genre")],
  604. ... "order_by": "released__year",
  605. ... }
  606. >>> Movie.objects.annotate(
  607. ... avg_rating=Window(
  608. ... expression=Avg("rating"),
  609. ... **window,
  610. ... ),
  611. ... best=Window(
  612. ... expression=Max("rating"),
  613. ... **window,
  614. ... ),
  615. ... worst=Window(
  616. ... expression=Min("rating"),
  617. ... **window,
  618. ... ),
  619. ... )
  620. Filtering against window functions is supported as long as lookups are not
  621. disjunctive (not using ``OR`` or ``XOR`` as a connector) and against a queryset
  622. performing aggregation.
  623. For example, a query that relies on aggregation and has an ``OR``-ed filter
  624. against a window function and a field is not supported. Applying combined
  625. predicates post-aggregation could cause rows that would normally be excluded
  626. from groups to be included:
  627. .. code-block:: pycon
  628. >>> qs = Movie.objects.annotate(
  629. ... category_rank=Window(Rank(), partition_by="category", order_by="-rating"),
  630. ... scenes_count=Count("actors"),
  631. ... ).filter(Q(category_rank__lte=3) | Q(title__contains="Batman"))
  632. >>> list(qs)
  633. NotImplementedError: Heterogeneous disjunctive predicates against window functions
  634. are not implemented when performing conditional aggregation.
  635. .. versionchanged:: 4.2
  636. Support for filtering against window functions was added.
  637. Among Django's built-in database backends, MySQL 8.0.2+, PostgreSQL, and Oracle
  638. support window expressions. Support for different window expression features
  639. varies among the different databases. For example, the options in
  640. :meth:`~django.db.models.Expression.asc` and
  641. :meth:`~django.db.models.Expression.desc` may not be supported. Consult the
  642. documentation for your database as needed.
  643. .. _window-frames:
  644. Frames
  645. ~~~~~~
  646. For a window frame, you can choose either a range-based sequence of rows or an
  647. ordinary sequence of rows.
  648. .. class:: ValueRange(start=None, end=None)
  649. .. attribute:: frame_type
  650. This attribute is set to ``'RANGE'``.
  651. PostgreSQL has limited support for ``ValueRange`` and only supports use of
  652. the standard start and end points, such as ``CURRENT ROW`` and ``UNBOUNDED
  653. FOLLOWING``.
  654. .. class:: RowRange(start=None, end=None)
  655. .. attribute:: frame_type
  656. This attribute is set to ``'ROWS'``.
  657. Both classes return SQL with the template:
  658. .. code-block:: sql
  659. %(frame_type)s BETWEEN %(start)s AND %(end)s
  660. Frames narrow the rows that are used for computing the result. They shift from
  661. some start point to some specified end point. Frames can be used with and
  662. without partitions, but it's often a good idea to specify an ordering of the
  663. window to ensure a deterministic result. In a frame, a peer in a frame is a row
  664. with an equivalent value, or all rows if an ordering clause isn't present.
  665. The default starting point for a frame is ``UNBOUNDED PRECEDING`` which is the
  666. first row of the partition. The end point is always explicitly included in the
  667. SQL generated by the ORM and is by default ``UNBOUNDED FOLLOWING``. The default
  668. frame includes all rows from the partition to the last row in the set.
  669. The accepted values for the ``start`` and ``end`` arguments are ``None``, an
  670. integer, or zero. A negative integer for ``start`` results in ``N preceding``,
  671. while ``None`` yields ``UNBOUNDED PRECEDING``. For both ``start`` and ``end``,
  672. zero will return ``CURRENT ROW``. Positive integers are accepted for ``end``.
  673. There's a difference in what ``CURRENT ROW`` includes. When specified in
  674. ``ROWS`` mode, the frame starts or ends with the current row. When specified in
  675. ``RANGE`` mode, the frame starts or ends at the first or last peer according to
  676. the ordering clause. Thus, ``RANGE CURRENT ROW`` evaluates the expression for
  677. rows which have the same value specified by the ordering. Because the template
  678. includes both the ``start`` and ``end`` points, this may be expressed with::
  679. ValueRange(start=0, end=0)
  680. If a movie's "peers" are described as movies released by the same studio in the
  681. same genre in the same year, this ``RowRange`` example annotates each movie
  682. with the average rating of a movie's two prior and two following peers:
  683. .. code-block:: pycon
  684. >>> from django.db.models import Avg, F, RowRange, Window
  685. >>> Movie.objects.annotate(
  686. ... avg_rating=Window(
  687. ... expression=Avg("rating"),
  688. ... partition_by=[F("studio"), F("genre")],
  689. ... order_by="released__year",
  690. ... frame=RowRange(start=-2, end=2),
  691. ... ),
  692. ... )
  693. If the database supports it, you can specify the start and end points based on
  694. values of an expression in the partition. If the ``released`` field of the
  695. ``Movie`` model stores the release month of each movies, this ``ValueRange``
  696. example annotates each movie with the average rating of a movie's peers
  697. released between twelve months before and twelve months after the each movie:
  698. .. code-block:: pycon
  699. >>> from django.db.models import Avg, F, ValueRange, Window
  700. >>> Movie.objects.annotate(
  701. ... avg_rating=Window(
  702. ... expression=Avg("rating"),
  703. ... partition_by=[F("studio"), F("genre")],
  704. ... order_by="released__year",
  705. ... frame=ValueRange(start=-12, end=12),
  706. ... ),
  707. ... )
  708. .. currentmodule:: django.db.models
  709. Technical Information
  710. =====================
  711. Below you'll find technical implementation details that may be useful to
  712. library authors. The technical API and examples below will help with
  713. creating generic query expressions that can extend the built-in functionality
  714. that Django provides.
  715. Expression API
  716. --------------
  717. Query expressions implement the :ref:`query expression API <query-expression>`,
  718. but also expose a number of extra methods and attributes listed below. All
  719. query expressions must inherit from ``Expression()`` or a relevant
  720. subclass.
  721. When a query expression wraps another expression, it is responsible for
  722. calling the appropriate methods on the wrapped expression.
  723. .. class:: Expression
  724. .. attribute:: allowed_default
  725. .. versionadded:: 5.0
  726. Tells Django that this expression can be used in
  727. :attr:`Field.db_default`. Defaults to ``False``.
  728. .. attribute:: contains_aggregate
  729. Tells Django that this expression contains an aggregate and that a
  730. ``GROUP BY`` clause needs to be added to the query.
  731. .. attribute:: contains_over_clause
  732. Tells Django that this expression contains a
  733. :class:`~django.db.models.expressions.Window` expression. It's used,
  734. for example, to disallow window function expressions in queries that
  735. modify data.
  736. .. attribute:: filterable
  737. Tells Django that this expression can be referenced in
  738. :meth:`.QuerySet.filter`. Defaults to ``True``.
  739. .. attribute:: window_compatible
  740. Tells Django that this expression can be used as the source expression
  741. in :class:`~django.db.models.expressions.Window`. Defaults to
  742. ``False``.
  743. .. attribute:: empty_result_set_value
  744. Tells Django which value should be returned when the expression is used
  745. to apply a function over an empty result set. Defaults to
  746. :py:data:`NotImplemented` which forces the expression to be computed on
  747. the database.
  748. .. method:: resolve_expression(query=None, allow_joins=True, reuse=None, summarize=False, for_save=False)
  749. Provides the chance to do any preprocessing or validation of
  750. the expression before it's added to the query. ``resolve_expression()``
  751. must also be called on any nested expressions. A ``copy()`` of ``self``
  752. should be returned with any necessary transformations.
  753. ``query`` is the backend query implementation.
  754. ``allow_joins`` is a boolean that allows or denies the use of
  755. joins in the query.
  756. ``reuse`` is a set of reusable joins for multi-join scenarios.
  757. ``summarize`` is a boolean that, when ``True``, signals that the
  758. query being computed is a terminal aggregate query.
  759. ``for_save`` is a boolean that, when ``True``, signals that the query
  760. being executed is performing a create or update.
  761. .. method:: get_source_expressions()
  762. Returns an ordered list of inner expressions. For example:
  763. .. code-block:: pycon
  764. >>> Sum(F("foo")).get_source_expressions()
  765. [F('foo')]
  766. .. method:: set_source_expressions(expressions)
  767. Takes a list of expressions and stores them such that
  768. ``get_source_expressions()`` can return them.
  769. .. method:: relabeled_clone(change_map)
  770. Returns a clone (copy) of ``self``, with any column aliases relabeled.
  771. Column aliases are renamed when subqueries are created.
  772. ``relabeled_clone()`` should also be called on any nested expressions
  773. and assigned to the clone.
  774. ``change_map`` is a dictionary mapping old aliases to new aliases.
  775. Example::
  776. def relabeled_clone(self, change_map):
  777. clone = copy.copy(self)
  778. clone.expression = self.expression.relabeled_clone(change_map)
  779. return clone
  780. .. method:: convert_value(value, expression, connection)
  781. A hook allowing the expression to coerce ``value`` into a more
  782. appropriate type.
  783. ``expression`` is the same as ``self``.
  784. .. method:: get_group_by_cols()
  785. Responsible for returning the list of columns references by
  786. this expression. ``get_group_by_cols()`` should be called on any
  787. nested expressions. ``F()`` objects, in particular, hold a reference
  788. to a column.
  789. .. versionchanged:: 4.2
  790. The ``alias=None`` keyword argument was removed.
  791. .. method:: asc(nulls_first=None, nulls_last=None)
  792. Returns the expression ready to be sorted in ascending order.
  793. ``nulls_first`` and ``nulls_last`` define how null values are sorted.
  794. See :ref:`using-f-to-sort-null-values` for example usage.
  795. .. method:: desc(nulls_first=None, nulls_last=None)
  796. Returns the expression ready to be sorted in descending order.
  797. ``nulls_first`` and ``nulls_last`` define how null values are sorted.
  798. See :ref:`using-f-to-sort-null-values` for example usage.
  799. .. method:: reverse_ordering()
  800. Returns ``self`` with any modifications required to reverse the sort
  801. order within an ``order_by`` call. As an example, an expression
  802. implementing ``NULLS LAST`` would change its value to be
  803. ``NULLS FIRST``. Modifications are only required for expressions that
  804. implement sort order like ``OrderBy``. This method is called when
  805. :meth:`~django.db.models.query.QuerySet.reverse()` is called on a
  806. queryset.
  807. Writing your own Query Expressions
  808. ----------------------------------
  809. You can write your own query expression classes that use, and can integrate
  810. with, other query expressions. Let's step through an example by writing an
  811. implementation of the ``COALESCE`` SQL function, without using the built-in
  812. :ref:`Func() expressions <func-expressions>`.
  813. The ``COALESCE`` SQL function is defined as taking a list of columns or
  814. values. It will return the first column or value that isn't ``NULL``.
  815. We'll start by defining the template to be used for SQL generation and
  816. an ``__init__()`` method to set some attributes::
  817. import copy
  818. from django.db.models import Expression
  819. class Coalesce(Expression):
  820. template = "COALESCE( %(expressions)s )"
  821. def __init__(self, expressions, output_field):
  822. super().__init__(output_field=output_field)
  823. if len(expressions) < 2:
  824. raise ValueError("expressions must have at least 2 elements")
  825. for expression in expressions:
  826. if not hasattr(expression, "resolve_expression"):
  827. raise TypeError("%r is not an Expression" % expression)
  828. self.expressions = expressions
  829. We do some basic validation on the parameters, including requiring at least
  830. 2 columns or values, and ensuring they are expressions. We are requiring
  831. ``output_field`` here so that Django knows what kind of model field to assign
  832. the eventual result to.
  833. Now we implement the preprocessing and validation. Since we do not have
  834. any of our own validation at this point, we delegate to the nested
  835. expressions::
  836. def resolve_expression(
  837. self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False
  838. ):
  839. c = self.copy()
  840. c.is_summary = summarize
  841. for pos, expression in enumerate(self.expressions):
  842. c.expressions[pos] = expression.resolve_expression(
  843. query, allow_joins, reuse, summarize, for_save
  844. )
  845. return c
  846. Next, we write the method responsible for generating the SQL::
  847. def as_sql(self, compiler, connection, template=None):
  848. sql_expressions, sql_params = [], []
  849. for expression in self.expressions:
  850. sql, params = compiler.compile(expression)
  851. sql_expressions.append(sql)
  852. sql_params.extend(params)
  853. template = template or self.template
  854. data = {"expressions": ",".join(sql_expressions)}
  855. return template % data, sql_params
  856. def as_oracle(self, compiler, connection):
  857. """
  858. Example of vendor specific handling (Oracle in this case).
  859. Let's make the function name lowercase.
  860. """
  861. return self.as_sql(compiler, connection, template="coalesce( %(expressions)s )")
  862. ``as_sql()`` methods can support custom keyword arguments, allowing
  863. ``as_vendorname()`` methods to override data used to generate the SQL string.
  864. Using ``as_sql()`` keyword arguments for customization is preferable to
  865. mutating ``self`` within ``as_vendorname()`` methods as the latter can lead to
  866. errors when running on different database backends. If your class relies on
  867. class attributes to define data, consider allowing overrides in your
  868. ``as_sql()`` method.
  869. We generate the SQL for each of the ``expressions`` by using the
  870. ``compiler.compile()`` method, and join the result together with commas.
  871. Then the template is filled out with our data and the SQL and parameters
  872. are returned.
  873. We've also defined a custom implementation that is specific to the Oracle
  874. backend. The ``as_oracle()`` function will be called instead of ``as_sql()``
  875. if the Oracle backend is in use.
  876. Finally, we implement the rest of the methods that allow our query expression
  877. to play nice with other query expressions::
  878. def get_source_expressions(self):
  879. return self.expressions
  880. def set_source_expressions(self, expressions):
  881. self.expressions = expressions
  882. Let's see how it works:
  883. .. code-block:: pycon
  884. >>> from django.db.models import F, Value, CharField
  885. >>> qs = Company.objects.annotate(
  886. ... tagline=Coalesce(
  887. ... [F("motto"), F("ticker_name"), F("description"), Value("No Tagline")],
  888. ... output_field=CharField(),
  889. ... )
  890. ... )
  891. >>> for c in qs:
  892. ... print("%s: %s" % (c.name, c.tagline))
  893. ...
  894. Google: Do No Evil
  895. Apple: AAPL
  896. Yahoo: Internet Company
  897. Django Software Foundation: No Tagline
  898. .. _avoiding-sql-injection-in-query-expressions:
  899. Avoiding SQL injection
  900. ~~~~~~~~~~~~~~~~~~~~~~
  901. Since a ``Func``'s keyword arguments for ``__init__()`` (``**extra``) and
  902. ``as_sql()`` (``**extra_context``) are interpolated into the SQL string rather
  903. than passed as query parameters (where the database driver would escape them),
  904. they must not contain untrusted user input.
  905. For example, if ``substring`` is user-provided, this function is vulnerable to
  906. SQL injection::
  907. from django.db.models import Func
  908. class Position(Func):
  909. function = "POSITION"
  910. template = "%(function)s('%(substring)s' in %(expressions)s)"
  911. def __init__(self, expression, substring):
  912. # substring=substring is an SQL injection vulnerability!
  913. super().__init__(expression, substring=substring)
  914. This function generates an SQL string without any parameters. Since
  915. ``substring`` is passed to ``super().__init__()`` as a keyword argument, it's
  916. interpolated into the SQL string before the query is sent to the database.
  917. Here's a corrected rewrite::
  918. class Position(Func):
  919. function = "POSITION"
  920. arg_joiner = " IN "
  921. def __init__(self, expression, substring):
  922. super().__init__(substring, expression)
  923. With ``substring`` instead passed as a positional argument, it'll be passed as
  924. a parameter in the database query.
  925. Adding support in third-party database backends
  926. -----------------------------------------------
  927. If you're using a database backend that uses a different SQL syntax for a
  928. certain function, you can add support for it by monkey patching a new method
  929. onto the function's class.
  930. Let's say we're writing a backend for Microsoft's SQL Server which uses the SQL
  931. ``LEN`` instead of ``LENGTH`` for the :class:`~functions.Length` function.
  932. We'll monkey patch a new method called ``as_sqlserver()`` onto the ``Length``
  933. class::
  934. from django.db.models.functions import Length
  935. def sqlserver_length(self, compiler, connection):
  936. return self.as_sql(compiler, connection, function="LEN")
  937. Length.as_sqlserver = sqlserver_length
  938. You can also customize the SQL using the ``template`` parameter of ``as_sql()``.
  939. We use ``as_sqlserver()`` because ``django.db.connection.vendor`` returns
  940. ``sqlserver`` for the backend.
  941. Third-party backends can register their functions in the top level
  942. ``__init__.py`` file of the backend package or in a top level ``expressions.py``
  943. file (or package) that is imported from the top level ``__init__.py``.
  944. For user projects wishing to patch the backend that they're using, this code
  945. should live in an :meth:`AppConfig.ready()<django.apps.AppConfig.ready>` method.