expressions.txt 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188
  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, distinct=False, 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. .. attribute:: allow_distinct
  283. .. versionadded:: 2.2
  284. A class attribute determining whether or not this aggregate function
  285. allows passing a ``distinct`` keyword argument. If set to ``False``
  286. (default), ``TypeError`` is raised if ``distinct=True`` is passed.
  287. The ``expressions`` positional arguments can include expressions or the names
  288. of model fields. They will be converted to a string and used as the
  289. ``expressions`` placeholder within the ``template``.
  290. The ``output_field`` argument requires a model field instance, like
  291. ``IntegerField()`` or ``BooleanField()``, into which Django will load the value
  292. after it's retrieved from the database. Usually no arguments are needed when
  293. instantiating the model field as any arguments relating to data validation
  294. (``max_length``, ``max_digits``, etc.) will not be enforced on the expression's
  295. output value.
  296. Note that ``output_field`` is only required when Django is unable to determine
  297. what field type the result should be. Complex expressions that mix field types
  298. should define the desired ``output_field``. For example, adding an
  299. ``IntegerField()`` and a ``FloatField()`` together should probably have
  300. ``output_field=FloatField()`` defined.
  301. The ``distinct`` argument determines whether or not the aggregate function
  302. should be invoked for each distinct value of ``expressions`` (or set of
  303. values, for multiple ``expressions``). The argument is only supported on
  304. aggregates that have :attr:`~Aggregate.allow_distinct` set to ``True``.
  305. The ``filter`` argument takes a :class:`Q object <django.db.models.Q>` that's
  306. used to filter the rows that are aggregated. See :ref:`conditional-aggregation`
  307. and :ref:`filtering-on-annotations` for example usage.
  308. The ``**extra`` kwargs are ``key=value`` pairs that can be interpolated
  309. into the ``template`` attribute.
  310. .. versionadded:: 2.2
  311. The ``allow_distinct`` attribute and ``distinct`` argument were added.
  312. Creating your own Aggregate Functions
  313. -------------------------------------
  314. Creating your own aggregate is extremely easy. At a minimum, you need
  315. to define ``function``, but you can also completely customize the
  316. SQL that is generated. Here's a brief example::
  317. from django.db.models import Aggregate
  318. class Count(Aggregate):
  319. # supports COUNT(distinct field)
  320. function = 'COUNT'
  321. template = '%(function)s(%(distinct)s%(expressions)s)'
  322. def __init__(self, expression, distinct=False, **extra):
  323. super().__init__(
  324. expression,
  325. distinct='DISTINCT ' if distinct else '',
  326. output_field=IntegerField(),
  327. **extra
  328. )
  329. ``Value()`` expressions
  330. -----------------------
  331. .. class:: Value(value, output_field=None)
  332. A ``Value()`` object represents the smallest possible component of an
  333. expression: a simple value. When you need to represent the value of an integer,
  334. boolean, or string within an expression, you can wrap that value within a
  335. ``Value()``.
  336. You will rarely need to use ``Value()`` directly. When you write the expression
  337. ``F('field') + 1``, Django implicitly wraps the ``1`` in a ``Value()``,
  338. allowing simple values to be used in more complex expressions. You will need to
  339. use ``Value()`` when you want to pass a string to an expression. Most
  340. expressions interpret a string argument as the name of a field, like
  341. ``Lower('name')``.
  342. The ``value`` argument describes the value to be included in the expression,
  343. such as ``1``, ``True``, or ``None``. Django knows how to convert these Python
  344. values into their corresponding database type.
  345. The ``output_field`` argument should be a model field instance, like
  346. ``IntegerField()`` or ``BooleanField()``, into which Django will load the value
  347. after it's retrieved from the database. Usually no arguments are needed when
  348. instantiating the model field as any arguments relating to data validation
  349. (``max_length``, ``max_digits``, etc.) will not be enforced on the expression's
  350. output value.
  351. ``ExpressionWrapper()`` expressions
  352. -----------------------------------
  353. .. class:: ExpressionWrapper(expression, output_field)
  354. ``ExpressionWrapper`` simply surrounds another expression and provides access
  355. to properties, such as ``output_field``, that may not be available on other
  356. expressions. ``ExpressionWrapper`` is necessary when using arithmetic on
  357. ``F()`` expressions with different types as described in
  358. :ref:`using-f-with-annotations`.
  359. Conditional expressions
  360. -----------------------
  361. Conditional expressions allow you to use :keyword:`if` ... :keyword:`elif` ...
  362. :keyword:`else` logic in queries. Django natively supports SQL ``CASE``
  363. expressions. For more details see :doc:`conditional-expressions`.
  364. ``Subquery()`` expressions
  365. --------------------------
  366. .. class:: Subquery(queryset, output_field=None)
  367. You can add an explicit subquery to a ``QuerySet`` using the ``Subquery``
  368. expression.
  369. For example, to annotate each post with the email address of the author of the
  370. newest comment on that post::
  371. >>> from django.db.models import OuterRef, Subquery
  372. >>> newest = Comment.objects.filter(post=OuterRef('pk')).order_by('-created_at')
  373. >>> Post.objects.annotate(newest_commenter_email=Subquery(newest.values('email')[:1]))
  374. On PostgreSQL, the SQL looks like:
  375. .. code-block:: sql
  376. SELECT "post"."id", (
  377. SELECT U0."email"
  378. FROM "comment" U0
  379. WHERE U0."post_id" = ("post"."id")
  380. ORDER BY U0."created_at" DESC LIMIT 1
  381. ) AS "newest_commenter_email" FROM "post"
  382. .. note::
  383. The examples in this section are designed to show how to force
  384. Django to execute a subquery. In some cases it may be possible to
  385. write an equivalent queryset that performs the same task more
  386. clearly or efficiently.
  387. Referencing columns from the outer queryset
  388. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  389. .. class:: OuterRef(field)
  390. Use ``OuterRef`` when a queryset in a ``Subquery`` needs to refer to a field
  391. from the outer query. It acts like an :class:`F` expression except that the
  392. check to see if it refers to a valid field isn't made until the outer queryset
  393. is resolved.
  394. Instances of ``OuterRef`` may be used in conjunction with nested instances
  395. of ``Subquery`` to refer to a containing queryset that isn't the immediate
  396. parent. For example, this queryset would need to be within a nested pair of
  397. ``Subquery`` instances to resolve correctly::
  398. >>> Book.objects.filter(author=OuterRef(OuterRef('pk')))
  399. Limiting a subquery to a single column
  400. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  401. There are times when a single column must be returned from a ``Subquery``, for
  402. instance, to use a ``Subquery`` as the target of an ``__in`` lookup. To return
  403. all comments for posts published within the last day::
  404. >>> from datetime import timedelta
  405. >>> from django.utils import timezone
  406. >>> one_day_ago = timezone.now() - timedelta(days=1)
  407. >>> posts = Post.objects.filter(published_at__gte=one_day_ago)
  408. >>> Comment.objects.filter(post__in=Subquery(posts.values('pk')))
  409. In this case, the subquery must use :meth:`~.QuerySet.values`
  410. to return only a single column: the primary key of the post.
  411. Limiting the subquery to a single row
  412. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  413. To prevent a subquery from returning multiple rows, a slice (``[:1]``) of the
  414. queryset is used::
  415. >>> subquery = Subquery(newest.values('email')[:1])
  416. >>> Post.objects.annotate(newest_commenter_email=subquery)
  417. In this case, the subquery must only return a single column *and* a single
  418. row: the email address of the most recently created comment.
  419. (Using :meth:`~.QuerySet.get` instead of a slice would fail because the
  420. ``OuterRef`` cannot be resolved until the queryset is used within a
  421. ``Subquery``.)
  422. ``Exists()`` subqueries
  423. ~~~~~~~~~~~~~~~~~~~~~~~
  424. .. class:: Exists(queryset)
  425. ``Exists`` is a ``Subquery`` subclass that uses an SQL ``EXISTS`` statement. In
  426. many cases it will perform better than a subquery since the database is able to
  427. stop evaluation of the subquery when a first matching row is found.
  428. For example, to annotate each post with whether or not it has a comment from
  429. within the last day::
  430. >>> from django.db.models import Exists, OuterRef
  431. >>> from datetime import timedelta
  432. >>> from django.utils import timezone
  433. >>> one_day_ago = timezone.now() - timedelta(days=1)
  434. >>> recent_comments = Comment.objects.filter(
  435. ... post=OuterRef('pk'),
  436. ... created_at__gte=one_day_ago,
  437. ... )
  438. >>> Post.objects.annotate(recent_comment=Exists(recent_comments))
  439. On PostgreSQL, the SQL looks like:
  440. .. code-block:: sql
  441. SELECT "post"."id", "post"."published_at", EXISTS(
  442. SELECT U0."id", U0."post_id", U0."email", U0."created_at"
  443. FROM "comment" U0
  444. WHERE (
  445. U0."created_at" >= YYYY-MM-DD HH:MM:SS AND
  446. U0."post_id" = ("post"."id")
  447. )
  448. ) AS "recent_comment" FROM "post"
  449. It's unnecessary to force ``Exists`` to refer to a single column, since the
  450. columns are discarded and a boolean result is returned. Similarly, since
  451. ordering is unimportant within an SQL ``EXISTS`` subquery and would only
  452. degrade performance, it's automatically removed.
  453. You can query using ``NOT EXISTS`` with ``~Exists()``.
  454. Filtering on a ``Subquery`` expression
  455. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  456. It's not possible to filter directly using ``Subquery`` and ``Exists``, e.g.::
  457. >>> Post.objects.filter(Exists(recent_comments))
  458. ...
  459. TypeError: 'Exists' object is not iterable
  460. You must filter on a subquery expression by first annotating the queryset
  461. and then filtering based on that annotation::
  462. >>> Post.objects.annotate(
  463. ... recent_comment=Exists(recent_comments),
  464. ... ).filter(recent_comment=True)
  465. Using aggregates within a ``Subquery`` expression
  466. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  467. Aggregates may be used within a ``Subquery``, but they require a specific
  468. combination of :meth:`~.QuerySet.filter`, :meth:`~.QuerySet.values`, and
  469. :meth:`~.QuerySet.annotate` to get the subquery grouping correct.
  470. Assuming both models have a ``length`` field, to find posts where the post
  471. length is greater than the total length of all combined comments::
  472. >>> from django.db.models import OuterRef, Subquery, Sum
  473. >>> comments = Comment.objects.filter(post=OuterRef('pk')).order_by().values('post')
  474. >>> total_comments = comments.annotate(total=Sum('length')).values('total')
  475. >>> Post.objects.filter(length__gt=Subquery(total_comments))
  476. The initial ``filter(...)`` limits the subquery to the relevant parameters.
  477. ``order_by()`` removes the default :attr:`~django.db.models.Options.ordering`
  478. (if any) on the ``Comment`` model. ``values('post')`` aggregates comments by
  479. ``Post``. Finally, ``annotate(...)`` performs the aggregation. The order in
  480. which these queryset methods are applied is important. In this case, since the
  481. subquery must be limited to a single column, ``values('total')`` is required.
  482. This is the only way to perform an aggregation within a ``Subquery``, as
  483. using :meth:`~.QuerySet.aggregate` attempts to evaluate the queryset (and if
  484. there is an ``OuterRef``, this will not be possible to resolve).
  485. Raw SQL expressions
  486. -------------------
  487. .. currentmodule:: django.db.models.expressions
  488. .. class:: RawSQL(sql, params, output_field=None)
  489. Sometimes database expressions can't easily express a complex ``WHERE`` clause.
  490. In these edge cases, use the ``RawSQL`` expression. For example::
  491. >>> from django.db.models.expressions import RawSQL
  492. >>> queryset.annotate(val=RawSQL("select col from sometable where othercol = %s", (someparam,)))
  493. These extra lookups may not be portable to different database engines (because
  494. you're explicitly writing SQL code) and violate the DRY principle, so you
  495. should avoid them if possible.
  496. .. warning::
  497. To protect against `SQL injection attacks
  498. <https://en.wikipedia.org/wiki/SQL_injection>`_, you must escape any
  499. parameters that the user can control by using ``params``. ``params`` is a
  500. required argument to force you to acknowledge that you're not interpolating
  501. your SQL with user-provided data.
  502. You also must not quote placeholders in the SQL string. This example is
  503. vulnerable to SQL injection because of the quotes around ``%s``::
  504. RawSQL("select col from sometable where othercol = '%s'") # unsafe!
  505. You can read more about how Django's :ref:`SQL injection protection
  506. <sql-injection-protection>` works.
  507. Window functions
  508. ----------------
  509. Window functions provide a way to apply functions on partitions. Unlike a
  510. normal aggregation function which computes a final result for each set defined
  511. by the group by, window functions operate on :ref:`frames <window-frames>` and
  512. partitions, and compute the result for each row.
  513. You can specify multiple windows in the same query which in Django ORM would be
  514. equivalent to including multiple expressions in a :doc:`QuerySet.annotate()
  515. </topics/db/aggregation>` call. The ORM doesn't make use of named windows,
  516. instead they are part of the selected columns.
  517. .. class:: Window(expression, partition_by=None, order_by=None, frame=None, output_field=None)
  518. .. attribute:: filterable
  519. Defaults to ``False``. The SQL standard disallows referencing window
  520. functions in the ``WHERE`` clause and Django raises an exception when
  521. constructing a ``QuerySet`` that would do that.
  522. .. attribute:: template
  523. Defaults to ``%(expression)s OVER (%(window)s)'``. If only the
  524. ``expression`` argument is provided, the window clause will be blank.
  525. The ``Window`` class is the main expression for an ``OVER`` clause.
  526. The ``expression`` argument is either a :ref:`window function
  527. <window-functions>`, an :ref:`aggregate function <aggregation-functions>`, or
  528. an expression that's compatible in a window clause.
  529. The ``partition_by`` argument is a list of expressions (column names should be
  530. wrapped in an ``F``-object) that control the partitioning of the rows.
  531. Partitioning narrows which rows are used to compute the result set.
  532. The ``output_field`` is specified either as an argument or by the expression.
  533. The ``order_by`` argument accepts a sequence of expressions on which you can
  534. call :meth:`~django.db.models.Expression.asc` and
  535. :meth:`~django.db.models.Expression.desc`. The ordering controls the order in
  536. which the expression is applied. For example, if you sum over the rows in a
  537. partition, the first result is just the value of the first row, the second is
  538. the sum of first and second row.
  539. The ``frame`` parameter specifies which other rows that should be used in the
  540. computation. See :ref:`window-frames` for details.
  541. For example, to annotate each movie with the average rating for the movies by
  542. the same studio in the same genre and release year::
  543. >>> from django.db.models import Avg, F, Window
  544. >>> from django.db.models.functions import ExtractYear
  545. >>> Movie.objects.annotate(
  546. >>> avg_rating=Window(
  547. >>> expression=Avg('rating'),
  548. >>> partition_by=[F('studio'), F('genre')],
  549. >>> order_by=ExtractYear('released').asc(),
  550. >>> ),
  551. >>> )
  552. This makes it easy to check if a movie is rated better or worse than its peers.
  553. You may want to apply multiple expressions over the same window, i.e., the
  554. same partition and frame. For example, you could modify the previous example
  555. to also include the best and worst rating in each movie's group (same studio,
  556. genre, and release year) by using three window functions in the same query. The
  557. partition and ordering from the previous example is extracted into a dictionary
  558. to reduce repetition::
  559. >>> from django.db.models import Avg, F, Max, Min, Window
  560. >>> from django.db.models.functions import ExtractYear
  561. >>> window = {
  562. >>> 'partition_by': [F('studio'), F('genre')],
  563. >>> 'order_by': ExtractYear('released').asc(),
  564. >>> }
  565. >>> Movie.objects.annotate(
  566. >>> avg_rating=Window(
  567. >>> expression=Avg('rating'), **window,
  568. >>> ),
  569. >>> best=Window(
  570. >>> expression=Max('rating'), **window,
  571. >>> ),
  572. >>> worst=Window(
  573. >>> expression=Min('rating'), **window,
  574. >>> ),
  575. >>> )
  576. Among Django's built-in database backends, MySQL 8.0.2+, PostgreSQL, and Oracle
  577. support window expressions. Support for different window expression features
  578. varies among the different databases. For example, the options in
  579. :meth:`~django.db.models.Expression.asc` and
  580. :meth:`~django.db.models.Expression.desc` may not be supported. Consult the
  581. documentation for your database as needed.
  582. .. _window-frames:
  583. Frames
  584. ~~~~~~
  585. For a window frame, you can choose either a range-based sequence of rows or an
  586. ordinary sequence of rows.
  587. .. class:: ValueRange(start=None, end=None)
  588. .. attribute:: frame_type
  589. This attribute is set to ``'RANGE'``.
  590. PostgreSQL has limited support for ``ValueRange`` and only supports use of
  591. the standard start and end points, such as ``CURRENT ROW`` and ``UNBOUNDED
  592. FOLLOWING``.
  593. .. class:: RowRange(start=None, end=None)
  594. .. attribute:: frame_type
  595. This attribute is set to ``'ROWS'``.
  596. Both classes return SQL with the template::
  597. %(frame_type)s BETWEEN %(start)s AND %(end)s
  598. Frames narrow the rows that are used for computing the result. They shift from
  599. some start point to some specified end point. Frames can be used with and
  600. without partitions, but it's often a good idea to specify an ordering of the
  601. window to ensure a deterministic result. In a frame, a peer in a frame is a row
  602. with an equivalent value, or all rows if an ordering clause isn't present.
  603. The default starting point for a frame is ``UNBOUNDED PRECEDING`` which is the
  604. first row of the partition. The end point is always explicitly included in the
  605. SQL generated by the ORM and is by default ``UNBOUNDED FOLLOWING``. The default
  606. frame includes all rows from the partition to the last row in the set.
  607. The accepted values for the ``start`` and ``end`` arguments are ``None``, an
  608. integer, or zero. A negative integer for ``start`` results in ``N preceding``,
  609. while ``None`` yields ``UNBOUNDED PRECEDING``. For both ``start`` and ``end``,
  610. zero will return ``CURRENT ROW``. Positive integers are accepted for ``end``.
  611. There's a difference in what ``CURRENT ROW`` includes. When specified in
  612. ``ROWS`` mode, the frame starts or ends with the current row. When specified in
  613. ``RANGE`` mode, the frame starts or ends at the first or last peer according to
  614. the ordering clause. Thus, ``RANGE CURRENT ROW`` evaluates the expression for
  615. rows which have the same value specified by the ordering. Because the template
  616. includes both the ``start`` and ``end`` points, this may be expressed with::
  617. ValueRange(start=0, end=0)
  618. If a movie's "peers" are described as movies released by the same studio in the
  619. same genre in the same year, this ``RowRange`` example annotates each movie
  620. with the average rating of a movie's two prior and two following peers::
  621. >>> from django.db.models import Avg, F, RowRange, Window
  622. >>> from django.db.models.functions import ExtractYear
  623. >>> Movie.objects.annotate(
  624. >>> avg_rating=Window(
  625. >>> expression=Avg('rating'),
  626. >>> partition_by=[F('studio'), F('genre')],
  627. >>> order_by=ExtractYear('released').asc(),
  628. >>> frame=RowRange(start=-2, end=2),
  629. >>> ),
  630. >>> )
  631. If the database supports it, you can specify the start and end points based on
  632. values of an expression in the partition. If the ``released`` field of the
  633. ``Movie`` model stores the release month of each movies, this ``ValueRange``
  634. example annotates each movie with the average rating of a movie's peers
  635. released between twelve months before and twelve months after the each movie.
  636. >>> from django.db.models import Avg, ExpressionList, F, ValueRange, Window
  637. >>> Movie.objects.annotate(
  638. >>> avg_rating=Window(
  639. >>> expression=Avg('rating'),
  640. >>> partition_by=[F('studio'), F('genre')],
  641. >>> order_by=F('released').asc(),
  642. >>> frame=ValueRange(start=-12, end=12),
  643. >>> ),
  644. >>> )
  645. .. currentmodule:: django.db.models
  646. Technical Information
  647. =====================
  648. Below you'll find technical implementation details that may be useful to
  649. library authors. The technical API and examples below will help with
  650. creating generic query expressions that can extend the built-in functionality
  651. that Django provides.
  652. Expression API
  653. --------------
  654. Query expressions implement the :ref:`query expression API <query-expression>`,
  655. but also expose a number of extra methods and attributes listed below. All
  656. query expressions must inherit from ``Expression()`` or a relevant
  657. subclass.
  658. When a query expression wraps another expression, it is responsible for
  659. calling the appropriate methods on the wrapped expression.
  660. .. class:: Expression
  661. .. attribute:: contains_aggregate
  662. Tells Django that this expression contains an aggregate and that a
  663. ``GROUP BY`` clause needs to be added to the query.
  664. .. attribute:: contains_over_clause
  665. Tells Django that this expression contains a
  666. :class:`~django.db.models.expressions.Window` expression. It's used,
  667. for example, to disallow window function expressions in queries that
  668. modify data.
  669. .. attribute:: filterable
  670. Tells Django that this expression can be referenced in
  671. :meth:`.QuerySet.filter`. Defaults to ``True``.
  672. .. attribute:: window_compatible
  673. Tells Django that this expression can be used as the source expression
  674. in :class:`~django.db.models.expressions.Window`. Defaults to
  675. ``False``.
  676. .. method:: resolve_expression(query=None, allow_joins=True, reuse=None, summarize=False, for_save=False)
  677. Provides the chance to do any pre-processing or validation of
  678. the expression before it's added to the query. ``resolve_expression()``
  679. must also be called on any nested expressions. A ``copy()`` of ``self``
  680. should be returned with any necessary transformations.
  681. ``query`` is the backend query implementation.
  682. ``allow_joins`` is a boolean that allows or denies the use of
  683. joins in the query.
  684. ``reuse`` is a set of reusable joins for multi-join scenarios.
  685. ``summarize`` is a boolean that, when ``True``, signals that the
  686. query being computed is a terminal aggregate query.
  687. .. method:: get_source_expressions()
  688. Returns an ordered list of inner expressions. For example::
  689. >>> Sum(F('foo')).get_source_expressions()
  690. [F('foo')]
  691. .. method:: set_source_expressions(expressions)
  692. Takes a list of expressions and stores them such that
  693. ``get_source_expressions()`` can return them.
  694. .. method:: relabeled_clone(change_map)
  695. Returns a clone (copy) of ``self``, with any column aliases relabeled.
  696. Column aliases are renamed when subqueries are created.
  697. ``relabeled_clone()`` should also be called on any nested expressions
  698. and assigned to the clone.
  699. ``change_map`` is a dictionary mapping old aliases to new aliases.
  700. Example::
  701. def relabeled_clone(self, change_map):
  702. clone = copy.copy(self)
  703. clone.expression = self.expression.relabeled_clone(change_map)
  704. return clone
  705. .. method:: convert_value(value, expression, connection)
  706. A hook allowing the expression to coerce ``value`` into a more
  707. appropriate type.
  708. .. method:: get_group_by_cols()
  709. Responsible for returning the list of columns references by
  710. this expression. ``get_group_by_cols()`` should be called on any
  711. nested expressions. ``F()`` objects, in particular, hold a reference
  712. to a column.
  713. .. method:: asc(nulls_first=False, nulls_last=False)
  714. Returns the expression ready to be sorted in ascending order.
  715. ``nulls_first`` and ``nulls_last`` define how null values are sorted.
  716. See :ref:`using-f-to-sort-null-values` for example usage.
  717. .. method:: desc(nulls_first=False, nulls_last=False)
  718. Returns the expression ready to be sorted in descending 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:: reverse_ordering()
  722. Returns ``self`` with any modifications required to reverse the sort
  723. order within an ``order_by`` call. As an example, an expression
  724. implementing ``NULLS LAST`` would change its value to be
  725. ``NULLS FIRST``. Modifications are only required for expressions that
  726. implement sort order like ``OrderBy``. This method is called when
  727. :meth:`~django.db.models.query.QuerySet.reverse()` is called on a
  728. queryset.
  729. Writing your own Query Expressions
  730. ----------------------------------
  731. You can write your own query expression classes that use, and can integrate
  732. with, other query expressions. Let's step through an example by writing an
  733. implementation of the ``COALESCE`` SQL function, without using the built-in
  734. :ref:`Func() expressions <func-expressions>`.
  735. The ``COALESCE`` SQL function is defined as taking a list of columns or
  736. values. It will return the first column or value that isn't ``NULL``.
  737. We'll start by defining the template to be used for SQL generation and
  738. an ``__init__()`` method to set some attributes::
  739. import copy
  740. from django.db.models import Expression
  741. class Coalesce(Expression):
  742. template = 'COALESCE( %(expressions)s )'
  743. def __init__(self, expressions, output_field):
  744. super().__init__(output_field=output_field)
  745. if len(expressions) < 2:
  746. raise ValueError('expressions must have at least 2 elements')
  747. for expression in expressions:
  748. if not hasattr(expression, 'resolve_expression'):
  749. raise TypeError('%r is not an Expression' % expression)
  750. self.expressions = expressions
  751. We do some basic validation on the parameters, including requiring at least
  752. 2 columns or values, and ensuring they are expressions. We are requiring
  753. ``output_field`` here so that Django knows what kind of model field to assign
  754. the eventual result to.
  755. Now we implement the pre-processing and validation. Since we do not have
  756. any of our own validation at this point, we just delegate to the nested
  757. expressions::
  758. def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False):
  759. c = self.copy()
  760. c.is_summary = summarize
  761. for pos, expression in enumerate(self.expressions):
  762. c.expressions[pos] = expression.resolve_expression(query, allow_joins, reuse, summarize, for_save)
  763. return c
  764. Next, we write the method responsible for generating the SQL::
  765. def as_sql(self, compiler, connection, template=None):
  766. sql_expressions, sql_params = [], []
  767. for expression in self.expressions:
  768. sql, params = compiler.compile(expression)
  769. sql_expressions.append(sql)
  770. sql_params.extend(params)
  771. template = template or self.template
  772. data = {'expressions': ','.join(sql_expressions)}
  773. return template % data, params
  774. def as_oracle(self, compiler, connection):
  775. """
  776. Example of vendor specific handling (Oracle in this case).
  777. Let's make the function name lowercase.
  778. """
  779. return self.as_sql(compiler, connection, template='coalesce( %(expressions)s )')
  780. ``as_sql()`` methods can support custom keyword arguments, allowing
  781. ``as_vendorname()`` methods to override data used to generate the SQL string.
  782. Using ``as_sql()`` keyword arguments for customization is preferable to
  783. mutating ``self`` within ``as_vendorname()`` methods as the latter can lead to
  784. errors when running on different database backends. If your class relies on
  785. class attributes to define data, consider allowing overrides in your
  786. ``as_sql()`` method.
  787. We generate the SQL for each of the ``expressions`` by using the
  788. ``compiler.compile()`` method, and join the result together with commas.
  789. Then the template is filled out with our data and the SQL and parameters
  790. are returned.
  791. We've also defined a custom implementation that is specific to the Oracle
  792. backend. The ``as_oracle()`` function will be called instead of ``as_sql()``
  793. if the Oracle backend is in use.
  794. Finally, we implement the rest of the methods that allow our query expression
  795. to play nice with other query expressions::
  796. def get_source_expressions(self):
  797. return self.expressions
  798. def set_source_expressions(self, expressions):
  799. self.expressions = expressions
  800. Let's see how it works::
  801. >>> from django.db.models import F, Value, CharField
  802. >>> qs = Company.objects.annotate(
  803. ... tagline=Coalesce([
  804. ... F('motto'),
  805. ... F('ticker_name'),
  806. ... F('description'),
  807. ... Value('No Tagline')
  808. ... ], output_field=CharField()))
  809. >>> for c in qs:
  810. ... print("%s: %s" % (c.name, c.tagline))
  811. ...
  812. Google: Do No Evil
  813. Apple: AAPL
  814. Yahoo: Internet Company
  815. Django Software Foundation: No Tagline
  816. .. _avoiding-sql-injection-in-query-expressions:
  817. Avoiding SQL injection
  818. ~~~~~~~~~~~~~~~~~~~~~~
  819. Since a ``Func``'s keyword arguments for ``__init__()`` (``**extra``) and
  820. ``as_sql()`` (``**extra_context``) are interpolated into the SQL string rather
  821. than passed as query parameters (where the database driver would escape them),
  822. they must not contain untrusted user input.
  823. For example, if ``substring`` is user-provided, this function is vulnerable to
  824. SQL injection::
  825. from django.db.models import Func
  826. class Position(Func):
  827. function = 'POSITION'
  828. template = "%(function)s('%(substring)s' in %(expressions)s)"
  829. def __init__(self, expression, substring):
  830. # substring=substring is a SQL injection vulnerability!
  831. super().__init__(expression, substring=substring)
  832. This function generates a SQL string without any parameters. Since ``substring``
  833. is passed to ``super().__init__()`` as a keyword argument, it's interpolated
  834. into the SQL string before the query is sent to the database.
  835. Here's a corrected rewrite::
  836. class Position(Func):
  837. function = 'POSITION'
  838. arg_joiner = ' IN '
  839. def __init__(self, expression, substring):
  840. super().__init__(substring, expression)
  841. With ``substring`` instead passed as a positional argument, it'll be passed as
  842. a parameter in the database query.
  843. Adding support in third-party database backends
  844. -----------------------------------------------
  845. If you're using a database backend that uses a different SQL syntax for a
  846. certain function, you can add support for it by monkey patching a new method
  847. onto the function's class.
  848. Let's say we're writing a backend for Microsoft's SQL Server which uses the SQL
  849. ``LEN`` instead of ``LENGTH`` for the :class:`~functions.Length` function.
  850. We'll monkey patch a new method called ``as_sqlserver()`` onto the ``Length``
  851. class::
  852. from django.db.models.functions import Length
  853. def sqlserver_length(self, compiler, connection):
  854. return self.as_sql(compiler, connection, function='LEN')
  855. Length.as_sqlserver = sqlserver_length
  856. You can also customize the SQL using the ``template`` parameter of ``as_sql()``.
  857. We use ``as_sqlserver()`` because ``django.db.connection.vendor`` returns
  858. ``sqlserver`` for the backend.
  859. Third-party backends can register their functions in the top level
  860. ``__init__.py`` file of the backend package or in a top level ``expressions.py``
  861. file (or package) that is imported from the top level ``__init__.py``.
  862. For user projects wishing to patch the backend that they're using, this code
  863. should live in an :meth:`AppConfig.ready()<django.apps.AppConfig.ready>` method.