expressions.txt 47 KB

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