expressions.txt 26 KB

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