expressions.txt 50 KB

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