expressions.txt 42 KB

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