conditional-expressions.txt 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. =======================
  2. Conditional Expressions
  3. =======================
  4. .. currentmodule:: django.db.models.expressions
  5. Conditional expressions let you use :keyword:`if` ... :keyword:`elif` ...
  6. :keyword:`else` logic within filters, annotations, aggregations, and updates. A
  7. conditional expression evaluates a series of conditions for each row of a
  8. table and returns the matching result expression. Conditional expressions can
  9. also be combined and nested like other :doc:`expressions <expressions>`.
  10. The conditional expression classes
  11. ==================================
  12. We'll be using the following model in the subsequent examples::
  13. from django.db import models
  14. class Client(models.Model):
  15. REGULAR = 'R'
  16. GOLD = 'G'
  17. PLATINUM = 'P'
  18. ACCOUNT_TYPE_CHOICES = [
  19. (REGULAR, 'Regular'),
  20. (GOLD, 'Gold'),
  21. (PLATINUM, 'Platinum'),
  22. ]
  23. name = models.CharField(max_length=50)
  24. registered_on = models.DateField()
  25. account_type = models.CharField(
  26. max_length=1,
  27. choices=ACCOUNT_TYPE_CHOICES,
  28. default=REGULAR,
  29. )
  30. ``When``
  31. --------
  32. .. class:: When(condition=None, then=None, **lookups)
  33. A ``When()`` object is used to encapsulate a condition and its result for use
  34. in the conditional expression. Using a ``When()`` object is similar to using
  35. the :meth:`~django.db.models.query.QuerySet.filter` method. The condition can
  36. be specified using :ref:`field lookups <field-lookups>`,
  37. :class:`~django.db.models.Q` objects, or :class:`~django.db.models.Expression`
  38. objects that have an ``output_field`` that is a
  39. :class:`~django.db.models.BooleanField`. The result is provided using the
  40. ``then`` keyword.
  41. .. versionchanged:: 4.0
  42. Support for lookup expressions was added.
  43. Some examples::
  44. >>> from django.db.models import F, Q, When
  45. >>> # String arguments refer to fields; the following two examples are equivalent:
  46. >>> When(account_type=Client.GOLD, then='name')
  47. >>> When(account_type=Client.GOLD, then=F('name'))
  48. >>> # You can use field lookups in the condition
  49. >>> from datetime import date
  50. >>> When(registered_on__gt=date(2014, 1, 1),
  51. ... registered_on__lt=date(2015, 1, 1),
  52. ... then='account_type')
  53. >>> # Complex conditions can be created using Q objects
  54. >>> When(Q(name__startswith="John") | Q(name__startswith="Paul"),
  55. ... then='name')
  56. >>> # Condition can be created using boolean expressions.
  57. >>> from django.db.models import Exists, OuterRef
  58. >>> non_unique_account_type = Client.objects.filter(
  59. ... account_type=OuterRef('account_type'),
  60. ... ).exclude(pk=OuterRef('pk')).values('pk')
  61. >>> When(Exists(non_unique_account_type), then=Value('non unique'))
  62. >>> # Condition can be created using lookup expressions.
  63. >>> from django.db.models.lookups import GreaterThan, LessThan
  64. >>> When(
  65. ... GreaterThan(F('registered_on'), date(2014, 1, 1)) &
  66. ... LessThan(F('registered_on'), date(2015, 1, 1)),
  67. ... then='account_type',
  68. ... )
  69. Keep in mind that each of these values can be an expression.
  70. .. note::
  71. Since the ``then`` keyword argument is reserved for the result of the
  72. ``When()``, there is a potential conflict if a
  73. :class:`~django.db.models.Model` has a field named ``then``. This can be
  74. resolved in two ways::
  75. >>> When(then__exact=0, then=1)
  76. >>> When(Q(then=0), then=1)
  77. .. versionchanged:: 3.2
  78. Support for using the ``condition`` argument with ``lookups`` was added.
  79. ``Case``
  80. --------
  81. .. class:: Case(*cases, **extra)
  82. A ``Case()`` expression is like the :keyword:`if` ... :keyword:`elif` ...
  83. :keyword:`else` statement in ``Python``. Each ``condition`` in the provided
  84. ``When()`` objects is evaluated in order, until one evaluates to a
  85. truthful value. The ``result`` expression from the matching ``When()`` object
  86. is returned.
  87. An example::
  88. >>>
  89. >>> from datetime import date, timedelta
  90. >>> from django.db.models import Case, Value, When
  91. >>> Client.objects.create(
  92. ... name='Jane Doe',
  93. ... account_type=Client.REGULAR,
  94. ... registered_on=date.today() - timedelta(days=36))
  95. >>> Client.objects.create(
  96. ... name='James Smith',
  97. ... account_type=Client.GOLD,
  98. ... registered_on=date.today() - timedelta(days=5))
  99. >>> Client.objects.create(
  100. ... name='Jack Black',
  101. ... account_type=Client.PLATINUM,
  102. ... registered_on=date.today() - timedelta(days=10 * 365))
  103. >>> # Get the discount for each Client based on the account type
  104. >>> Client.objects.annotate(
  105. ... discount=Case(
  106. ... When(account_type=Client.GOLD, then=Value('5%')),
  107. ... When(account_type=Client.PLATINUM, then=Value('10%')),
  108. ... default=Value('0%'),
  109. ... ),
  110. ... ).values_list('name', 'discount')
  111. <QuerySet [('Jane Doe', '0%'), ('James Smith', '5%'), ('Jack Black', '10%')]>
  112. ``Case()`` accepts any number of ``When()`` objects as individual arguments.
  113. Other options are provided using keyword arguments. If none of the conditions
  114. evaluate to ``TRUE``, then the expression given with the ``default`` keyword
  115. argument is returned. If a ``default`` argument isn't provided, ``None`` is
  116. used.
  117. If we wanted to change our previous query to get the discount based on how long
  118. the ``Client`` has been with us, we could do so using lookups::
  119. >>> a_month_ago = date.today() - timedelta(days=30)
  120. >>> a_year_ago = date.today() - timedelta(days=365)
  121. >>> # Get the discount for each Client based on the registration date
  122. >>> Client.objects.annotate(
  123. ... discount=Case(
  124. ... When(registered_on__lte=a_year_ago, then=Value('10%')),
  125. ... When(registered_on__lte=a_month_ago, then=Value('5%')),
  126. ... default=Value('0%'),
  127. ... )
  128. ... ).values_list('name', 'discount')
  129. <QuerySet [('Jane Doe', '5%'), ('James Smith', '0%'), ('Jack Black', '10%')]>
  130. .. note::
  131. Remember that the conditions are evaluated in order, so in the above
  132. example we get the correct result even though the second condition matches
  133. both Jane Doe and Jack Black. This works just like an :keyword:`if` ...
  134. :keyword:`elif` ... :keyword:`else` statement in ``Python``.
  135. ``Case()`` also works in a ``filter()`` clause. For example, to find gold
  136. clients that registered more than a month ago and platinum clients that
  137. registered more than a year ago::
  138. >>> a_month_ago = date.today() - timedelta(days=30)
  139. >>> a_year_ago = date.today() - timedelta(days=365)
  140. >>> Client.objects.filter(
  141. ... registered_on__lte=Case(
  142. ... When(account_type=Client.GOLD, then=a_month_ago),
  143. ... When(account_type=Client.PLATINUM, then=a_year_ago),
  144. ... ),
  145. ... ).values_list('name', 'account_type')
  146. <QuerySet [('Jack Black', 'P')]>
  147. Advanced queries
  148. ================
  149. Conditional expressions can be used in annotations, aggregations, filters,
  150. lookups, and updates. They can also be combined and nested with other
  151. expressions. This allows you to make powerful conditional queries.
  152. Conditional update
  153. ------------------
  154. Let's say we want to change the ``account_type`` for our clients to match
  155. their registration dates. We can do this using a conditional expression and the
  156. :meth:`~django.db.models.query.QuerySet.update` method::
  157. >>> a_month_ago = date.today() - timedelta(days=30)
  158. >>> a_year_ago = date.today() - timedelta(days=365)
  159. >>> # Update the account_type for each Client from the registration date
  160. >>> Client.objects.update(
  161. ... account_type=Case(
  162. ... When(registered_on__lte=a_year_ago,
  163. ... then=Value(Client.PLATINUM)),
  164. ... When(registered_on__lte=a_month_ago,
  165. ... then=Value(Client.GOLD)),
  166. ... default=Value(Client.REGULAR)
  167. ... ),
  168. ... )
  169. >>> Client.objects.values_list('name', 'account_type')
  170. <QuerySet [('Jane Doe', 'G'), ('James Smith', 'R'), ('Jack Black', 'P')]>
  171. .. _conditional-aggregation:
  172. Conditional aggregation
  173. -----------------------
  174. What if we want to find out how many clients there are for each
  175. ``account_type``? We can use the ``filter`` argument of :ref:`aggregate
  176. functions <aggregation-functions>` to achieve this::
  177. >>> # Create some more Clients first so we can have something to count
  178. >>> Client.objects.create(
  179. ... name='Jean Grey',
  180. ... account_type=Client.REGULAR,
  181. ... registered_on=date.today())
  182. >>> Client.objects.create(
  183. ... name='James Bond',
  184. ... account_type=Client.PLATINUM,
  185. ... registered_on=date.today())
  186. >>> Client.objects.create(
  187. ... name='Jane Porter',
  188. ... account_type=Client.PLATINUM,
  189. ... registered_on=date.today())
  190. >>> # Get counts for each value of account_type
  191. >>> from django.db.models import Count
  192. >>> Client.objects.aggregate(
  193. ... regular=Count('pk', filter=Q(account_type=Client.REGULAR)),
  194. ... gold=Count('pk', filter=Q(account_type=Client.GOLD)),
  195. ... platinum=Count('pk', filter=Q(account_type=Client.PLATINUM)),
  196. ... )
  197. {'regular': 2, 'gold': 1, 'platinum': 3}
  198. This aggregate produces a query with the SQL 2003 ``FILTER WHERE`` syntax
  199. on databases that support it:
  200. .. code-block:: sql
  201. SELECT count('id') FILTER (WHERE account_type=1) as regular,
  202. count('id') FILTER (WHERE account_type=2) as gold,
  203. count('id') FILTER (WHERE account_type=3) as platinum
  204. FROM clients;
  205. On other databases, this is emulated using a ``CASE`` statement:
  206. .. code-block:: sql
  207. SELECT count(CASE WHEN account_type=1 THEN id ELSE null) as regular,
  208. count(CASE WHEN account_type=2 THEN id ELSE null) as gold,
  209. count(CASE WHEN account_type=3 THEN id ELSE null) as platinum
  210. FROM clients;
  211. The two SQL statements are functionally equivalent but the more explicit
  212. ``FILTER`` may perform better.
  213. Conditional filter
  214. ------------------
  215. When a conditional expression returns a boolean value, it is possible to use it
  216. directly in filters. This means that it will not be added to the ``SELECT``
  217. columns, but you can still use it to filter results::
  218. >>> non_unique_account_type = Client.objects.filter(
  219. ... account_type=OuterRef('account_type'),
  220. ... ).exclude(pk=OuterRef('pk')).values('pk')
  221. >>> Client.objects.filter(~Exists(non_unique_account_type))
  222. In SQL terms, that evaluates to:
  223. .. code-block:: sql
  224. SELECT ...
  225. FROM client c0
  226. WHERE NOT EXISTS (
  227. SELECT c1.id
  228. FROM client c1
  229. WHERE c1.account_type = c0.account_type AND NOT c1.id = c0.id
  230. )