expressions.txt 49 KB

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