expressions.txt 23 KB

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