expressions.txt 45 KB

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