conditional-expressions.txt 10 KB

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