expressions.txt 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  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. a filter, order by, annotation, or aggregate. There are a number of built-in
  7. expressions (documented below) that can be used to help you write queries.
  8. Expressions can be combined, or in some cases nested, to form more complex
  9. computations.
  10. Supported arithmetic
  11. ====================
  12. Django supports addition, subtraction, multiplication, division, modulo
  13. arithmetic, and the power operator on query expressions, using Python constants,
  14. variables, and even other expressions.
  15. Some examples
  16. =============
  17. .. versionchanged:: 1.8
  18. Some of the examples rely on functionality that is new in Django 1.8.
  19. .. code-block:: python
  20. # Find companies that have more employees than chairs.
  21. Company.objects.filter(num_employees__gt=F('num_chairs'))
  22. # Find companies that have at least twice as many employees
  23. # as chairs. Both the querysets below are equivalent.
  24. Company.objects.filter(num_employees__gt=F('num_chairs') * 2)
  25. Company.objects.filter(
  26. num_employees__gt=F('num_chairs') + F('num_chairs'))
  27. # How many chairs are needed for each company to seat all employees?
  28. >>> company = Company.objects.filter(
  29. ... num_employees__gt=F('num_chairs')).annotate(
  30. ... chairs_needed=F('num_employees') - F('num_chairs')).first()
  31. >>> company.num_employees
  32. 120
  33. >>> company.num_chairs
  34. 50
  35. >>> company.chairs_needed
  36. 70
  37. # Annotate models with an aggregated value. Both forms
  38. # below are equivalent.
  39. Company.objects.annotate(num_products=Count('products'))
  40. Company.objects.annotate(num_products=Count(F('products')))
  41. # Aggregates can contain complex computations also
  42. Company.objects.annotate(num_offerings=Count(F('products') + F('services')))
  43. # Expressions can also be used in order_by()
  44. Company.objects.order_by(Length('name').asc())
  45. Company.objects.order_by(Length('name').desc())
  46. Built-in Expressions
  47. ====================
  48. ``F()`` expressions
  49. -------------------
  50. .. class:: F
  51. An ``F()`` object represents the value of a model field or annotated column. It
  52. makes it possible to refer to model field values and perform database
  53. operations using them without actually having to pull them out of the database
  54. into Python memory.
  55. Instead, Django uses the ``F()`` object to generate a SQL expression that
  56. describes the required operation at the database level.
  57. This is easiest to understand through an example. Normally, one might do
  58. something like this::
  59. # Tintin filed a news story!
  60. reporter = Reporters.objects.get(name='Tintin')
  61. reporter.stories_filed += 1
  62. reporter.save()
  63. Here, we have pulled the value of ``reporter.stories_filed`` from the database
  64. into memory and manipulated it using familiar Python operators, and then saved
  65. the object back to the database. But instead we could also have done::
  66. from django.db.models import F
  67. reporter = Reporters.objects.get(name='Tintin')
  68. reporter.stories_filed = F('stories_filed') + 1
  69. reporter.save()
  70. Although ``reporter.stories_filed = F('stories_filed') + 1`` looks like a
  71. normal Python assignment of value to an instance attribute, in fact it's an SQL
  72. construct describing an operation on the database.
  73. When Django encounters an instance of ``F()``, it overrides the standard Python
  74. operators to create an encapsulated SQL expression; in this case, one which
  75. instructs the database to increment the database field represented by
  76. ``reporter.stories_filed``.
  77. Whatever value is or was on ``reporter.stories_filed``, Python never gets to
  78. know about it - it is dealt with entirely by the database. All Python does,
  79. through Django's ``F()`` class, is create the SQL syntax to refer to the field
  80. and describe the operation.
  81. .. note::
  82. In order to access the new value that has been saved in this way, the object
  83. will need to be reloaded::
  84. reporter = Reporters.objects.get(pk=reporter.pk)
  85. As well as being used in operations on single instances as above, ``F()`` can
  86. be used on ``QuerySets`` of object instances, with ``update()``. This reduces
  87. the two queries we were using above - the ``get()`` and the
  88. :meth:`~Model.save()` - to just one::
  89. reporter = Reporters.objects.filter(name='Tintin')
  90. reporter.update(stories_filed=F('stories_filed') + 1)
  91. We can also use :meth:`~django.db.models.query.QuerySet.update()` to increment
  92. the field value on multiple objects - which could be very much faster than
  93. pulling them all into Python from the database, looping over them, incrementing
  94. the field value of each one, and saving each one back to the database::
  95. Reporter.objects.all().update(stories_filed=F('stories_filed) + 1)
  96. ``F()`` therefore can offer performance advantages by:
  97. * getting the database, rather than Python, to do work
  98. * reducing the number of queries some operations require
  99. .. _avoiding-race-conditions-using-f:
  100. Avoiding race conditions using ``F()``
  101. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  102. Another useful benefit of ``F()`` is that having the database - rather than
  103. Python - update a field's value avoids a *race condition*.
  104. If two Python threads execute the code in the first example above, one thread
  105. could retrieve, increment, and save a field's value after the other has
  106. retrieved it from the database. The value that the second thread saves will be
  107. based on the original value; the work of the first thread will simply be lost.
  108. If the database is responsible for updating the field, the process is more
  109. robust: it will only ever update the field based on the value of the field in
  110. the database when the :meth:`~Model.save()` or ``update()`` is executed, rather
  111. than based on its value when the instance was retrieved.
  112. Using ``F()`` in filters
  113. ~~~~~~~~~~~~~~~~~~~~~~~~
  114. ``F()`` is also very useful in ``QuerySet`` filters, where they make it
  115. possible to filter a set of objects against criteria based on their field
  116. values, rather than on Python values.
  117. This is documented in :ref:`using F() expressions in queries
  118. <using-f-expressions-in-filters>`.
  119. .. _func-expressions:
  120. ``Func()`` expressions
  121. ----------------------
  122. .. versionadded:: 1.8
  123. ``Func()`` expressions are the base type of all expressions that involve
  124. database functions like ``COALESCE`` and ``LOWER``, or aggregates like ``SUM``.
  125. They can be used directly::
  126. queryset.annotate(field_lower=Func(F('field'), function='LOWER'))
  127. or they can be used to build a library of database functions::
  128. class Lower(Func):
  129. function = 'LOWER'
  130. queryset.annotate(field_lower=Lower(F('field')))
  131. But both cases will result in a queryset where each model is annotated with an
  132. extra attribute ``field_lower`` produced, roughly, from the following SQL::
  133. SELECT
  134. ...
  135. LOWER("app_label"."field") as "field_lower"
  136. See :doc:`database-functions` for a list of built-in database functions.
  137. The ``Func`` API is as follows:
  138. .. class:: Func(*expressions, **extra)
  139. .. attribute:: function
  140. A class attribute describing the function that will be generated.
  141. Specifically, the ``function`` will be interpolated as the ``function``
  142. placeholder within :attr:`template`. Defaults to ``None``.
  143. .. attribute:: template
  144. A class attribute, as a format string, that describes the SQL that is
  145. generated for this function. Defaults to
  146. ``'%(function)s(%(expressions)s)'``.
  147. .. attribute:: arg_joiner
  148. A class attribute that denotes the character used to join the list of
  149. ``expressions`` together. Defaults to ``', '``.
  150. The ``*expressions`` argument is a list of positional expressions that the
  151. function will be applied to. The expressions will be converted to strings,
  152. joined together with ``arg_joiner``, and then interpolated into the ``template``
  153. as the ``expressions`` placeholder.
  154. Positional arguments can be expressions or Python values. Strings are
  155. assumed to be column references and will be wrapped in ``F()`` expressions
  156. while other values will be wrapped in ``Value()`` expressions.
  157. The ``**extra`` kwargs are ``key=value`` pairs that can be interpolated
  158. into the ``template`` attribute. Note that the keywords ``function`` and
  159. ``template`` can be used to replace the ``function`` and ``template``
  160. attributes respectively, without having to define your own class.
  161. ``output_field`` can be used to define the expected return type.
  162. ``Aggregate()`` expressions
  163. ---------------------------
  164. An aggregate expression is a special case of a :ref:`Func() expression
  165. <func-expressions>` that informs the query that a ``GROUP BY`` clause
  166. is required. All of the :ref:`aggregate functions <aggregation-functions>`,
  167. like ``Sum()`` and ``Count()``, inherit from ``Aggregate()``.
  168. Since ``Aggregate``\s are expressions and wrap expressions, you can represent
  169. some complex computations::
  170. Company.objects.annotate(
  171. managers_required=(Count('num_employees') / 4) + Count('num_managers'))
  172. The ``Aggregate`` API is as follows:
  173. .. class:: Aggregate(expression, output_field=None, **extra)
  174. .. attribute:: template
  175. A class attribute, as a format string, that describes the SQL that is
  176. generated for this aggregate. Defaults to
  177. ``'%(function)s( %(expressions)s )'``.
  178. .. attribute:: function
  179. A class attribute describing the aggregate function that will be
  180. generated. Specifically, the ``function`` will be interpolated as the
  181. ``function`` placeholder within :attr:`template`. Defaults to ``None``.
  182. The ``expression`` argument can be the name of a field on the model, or another
  183. expression. It will be converted to a string and used as the ``expressions``
  184. placeholder within the ``template``.
  185. The ``output_field`` argument requires a model field instance, like
  186. ``IntegerField()`` or ``BooleanField()``, into which Django will load the value
  187. after it's retrieved from the database. Usually no arguments are needed when
  188. instantiating the model field as any arguments relating to data validation
  189. (``max_length``, ``max_digits``, etc.) will not be enforced on the expression's
  190. output value.
  191. Note that ``output_field`` is only required when Django is unable to determine
  192. what field type the result should be. Complex expressions that mix field types
  193. should define the desired ``output_field``. For example, adding an
  194. ``IntegerField()`` and a ``FloatField()`` together should probably have
  195. ``output_field=FloatField()`` defined.
  196. .. versionchanged:: 1.8
  197. ``output_field`` is a new parameter.
  198. The ``**extra`` kwargs are ``key=value`` pairs that can be interpolated
  199. into the ``template`` attribute.
  200. .. versionadded:: 1.8
  201. Aggregate functions can now use arithmetic and reference multiple
  202. model fields in a single function.
  203. Creating your own Aggregate Functions
  204. -------------------------------------
  205. Creating your own aggregate is extremely easy. At a minimum, you need
  206. to define ``function``, but you can also completely customize the
  207. SQL that is generated. Here's a brief example::
  208. class Count(Aggregate):
  209. # supports COUNT(distinct field)
  210. function = 'COUNT'
  211. template = '%(function)s(%(distinct)s%(expressions)s)'
  212. def __init__(self, expression, distinct=False, **extra):
  213. super(Count, self).__init__(
  214. expression,
  215. distinct='DISTINCT ' if distinct else '',
  216. output_field=IntegerField(),
  217. **extra)
  218. ``Value()`` expressions
  219. -----------------------
  220. .. class:: Value(value, output_field=None)
  221. A ``Value()`` object represents the smallest possible component of an
  222. expression: a simple value. When you need to represent the value of an integer,
  223. boolean, or string within an expression, you can wrap that value within a
  224. ``Value()``.
  225. You will rarely need to use ``Value()`` directly. When you write the expression
  226. ``F('field') + 1``, Django implicitly wraps the ``1`` in a ``Value()``,
  227. allowing simple values to be used in more complex expressions.
  228. The ``value`` argument describes the value to be included in the expression,
  229. such as ``1``, ``True``, or ``None``. Django knows how to convert these Python
  230. values into their corresponding database type.
  231. The ``output_field`` argument should be a model field instance, like
  232. ``IntegerField()`` or ``BooleanField()``, into which Django will load the value
  233. after it's retrieved from the database. Usually no arguments are needed when
  234. instantiating the model field as any arguments relating to data validation
  235. (``max_length``, ``max_digits``, etc.) will not be enforced on the expression's
  236. output value.
  237. Conditional expressions
  238. -----------------------
  239. .. versionadded:: 1.8
  240. Conditional expressions allow you to use :keyword:`if` ... :keyword:`elif` ...
  241. :keyword:`else` logic in queries. Django natively supports SQL ``CASE``
  242. expressions. For more details see :doc:`conditional-expressions`.
  243. Technical Information
  244. =====================
  245. Below you'll find technical implementation details that may be useful to
  246. library authors. The technical API and examples below will help with
  247. creating generic query expressions that can extend the built-in functionality
  248. that Django provides.
  249. Expression API
  250. --------------
  251. Query expressions implement the :ref:`query expression API <query-expression>`,
  252. but also expose a number of extra methods and attributes listed below. All
  253. query expressions must inherit from ``ExpressionNode()`` or a relevant
  254. subclass.
  255. When a query expression wraps another expression, it is responsible for
  256. calling the appropriate methods on the wrapped expression.
  257. .. class:: ExpressionNode
  258. .. attribute:: contains_aggregate
  259. Tells Django that this expression contains an aggregate and that a
  260. ``GROUP BY`` clause needs to be added to the query.
  261. .. method:: resolve_expression(query=None, allow_joins=True, reuse=None, summarize=False)
  262. Provides the chance to do any pre-processing or validation of
  263. the expression before it's added to the query. ``resolve_expression()``
  264. must also be called on any nested expressions. A ``copy()`` of ``self``
  265. should be returned with any necessary transformations.
  266. ``query`` is the backend query implementation.
  267. ``allow_joins`` is a boolean that allows or denies the use of
  268. joins in the query.
  269. ``reuse`` is a set of reusable joins for multi-join scenarios.
  270. ``summarize`` is a boolean that, when ``True``, signals that the
  271. query being computed is a terminal aggregate query.
  272. .. method:: get_source_expressions()
  273. Returns an ordered list of inner expressions. For example::
  274. >>> Sum(F('foo')).get_source_expressions()
  275. [F('foo')]
  276. .. method:: set_source_expressions(expressions)
  277. Takes a list of expressions and stores them such that
  278. ``get_source_expressions()`` can return them.
  279. .. method:: relabeled_clone(change_map)
  280. Returns a clone (copy) of ``self``, with any column aliases relabeled.
  281. Column aliases are renamed when subqueries are created.
  282. ``relabeled_clone()`` should also be called on any nested expressions
  283. and assigned to the clone.
  284. ``change_map`` is a dictionary mapping old aliases to new aliases.
  285. Example::
  286. def relabeled_clone(self, change_map):
  287. clone = copy.copy(self)
  288. clone.expression = self.expression.relabeled_clone(change_map)
  289. return clone
  290. .. method:: convert_value(self, value, connection, context)
  291. A hook allowing the expression to coerce ``value`` into a more
  292. appropriate type.
  293. .. method:: refs_aggregate(existing_aggregates)
  294. Returns a tuple containing the ``(aggregate, lookup_path)`` of the
  295. first aggregate that this expression (or any nested expression)
  296. references, or ``(False, ())`` if no aggregate is referenced.
  297. For example::
  298. queryset.filter(num_chairs__gt=F('sum__employees'))
  299. The ``F()`` expression here references a previous ``Sum()``
  300. computation which means that this filter expression should be
  301. added to the ``HAVING`` clause rather than the ``WHERE`` clause.
  302. In the majority of cases, returning the result of ``refs_aggregate``
  303. on any nested expression should be appropriate, as the necessary
  304. built-in expressions will return the correct values.
  305. .. method:: get_group_by_cols()
  306. Responsible for returning the list of columns references by
  307. this expression. ``get_group_by_cols()`` should be called on any
  308. nested expressions. ``F()`` objects, in particular, hold a reference
  309. to a column.
  310. .. method:: asc()
  311. Returns the expression ready to be sorted in ascending order.
  312. .. method:: desc()
  313. Returns the expression ready to be sorted in descending order.
  314. .. method:: reverse_ordering()
  315. Returns ``self`` with any modifications required to reverse the sort
  316. order within an ``order_by`` call. As an example, an expression
  317. implementing ``NULLS LAST`` would change its value to be
  318. ``NULLS FIRST``. Modifications are only required for expressions that
  319. implement sort order like ``OrderBy``. This method is called when
  320. :meth:`~django.db.models.query.QuerySet.reverse()` is called on a
  321. queryset.
  322. Writing your own Query Expressions
  323. ----------------------------------
  324. You can write your own query expression classes that use, and can integrate
  325. with, other query expressions. Let's step through an example by writing an
  326. implementation of the ``COALESCE`` SQL function, without using the built-in
  327. :ref:`Func() expressions <func-expressions>`.
  328. The ``COALESCE`` SQL function is defined as taking a list of columns or
  329. values. It will return the first column or value that isn't ``NULL``.
  330. We'll start by defining the template to be used for SQL generation and
  331. an ``__init__()`` method to set some attributes::
  332. import copy
  333. from django.db.models import ExpressionNode
  334. class Coalesce(ExpressionNode):
  335. template = 'COALESCE( %(expressions)s )'
  336. def __init__(self, expressions, output_field, **extra):
  337. super(Coalesce, self).__init__(output_field=output_field)
  338. if len(expressions) < 2:
  339. raise ValueError('expressions must have at least 2 elements')
  340. for expression in expressions:
  341. if not hasattr(expression, 'resolve_expression'):
  342. raise TypeError('%r is not an Expression' % expression)
  343. self.expressions = expressions
  344. self.extra = extra
  345. We do some basic validation on the parameters, including requiring at least
  346. 2 columns or values, and ensuring they are expressions. We are requiring
  347. ``output_field`` here so that Django knows what kind of model field to assign
  348. the eventual result to.
  349. Now we implement the pre-processing and validation. Since we do not have
  350. any of our own validation at this point, we just delegate to the nested
  351. expressions::
  352. def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False):
  353. c = self.copy()
  354. c.is_summary = summarize
  355. for pos, expression in enumerate(self.expressions):
  356. c.expressions[pos] = expression.resolve_expression(query, allow_joins, reuse, summarize)
  357. return c
  358. Next, we write the method responsible for generating the SQL::
  359. def as_sql(self, compiler, connection):
  360. sql_expressions, sql_params = [], []
  361. for expression in self.expressions:
  362. sql, params = compiler.compile(expression)
  363. sql_expressions.append(sql)
  364. sql_params.extend(params)
  365. self.extra['expressions'] = ','.join(sql_expressions)
  366. return self.template % self.extra, sql_params
  367. def as_oracle(self, compiler, connection):
  368. """
  369. Example of vendor specific handling (Oracle in this case).
  370. Let's make the function name lowercase.
  371. """
  372. self.template = 'coalesce( %(expressions)s )'
  373. return self.as_sql(compiler, connection)
  374. We generate the SQL for each of the ``expressions`` by using the
  375. ``compiler.compile()`` method, and join the result together with commas.
  376. Then the template is filled out with our data and the SQL and parameters
  377. are returned.
  378. We've also defined a custom implementation that is specific to the Oracle
  379. backend. The ``as_oracle()`` function will be called instead of ``as_sql()``
  380. if the Oracle backend is in use.
  381. Finally, we implement the rest of the methods that allow our query expression
  382. to play nice with other query expressions::
  383. def get_source_expressions(self):
  384. return self.expressions
  385. def set_source_expressions(expressions):
  386. self.expressions = expressions
  387. Let's see how it works::
  388. >>> qs = Company.objects.annotate(
  389. ... tagline=Coalesce([
  390. ... F('motto'),
  391. ... F('ticker_name'),
  392. ... F('description'),
  393. ... Value('No Tagline')
  394. ... ], output_field=CharField()))
  395. >>> for c in qs:
  396. ... print("%s: %s" % (c.name, c.tagline))
  397. ...
  398. Google: Do No Evil
  399. Apple: AAPL
  400. Yahoo: Internet Company
  401. Django Software Foundation: No Tagline