expressions.txt 50 KB

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