expressions.txt 20 KB

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