expressions.txt 45 KB

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