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