expressions.txt 46 KB

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