conditional-expressions.txt 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  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>` or
  37. :class:`~django.db.models.Q` objects. The result is provided using the ``then``
  38. keyword.
  39. Some examples::
  40. >>> from django.db.models import When, F, Q
  41. >>> # String arguments refer to fields; the following two examples are equivalent:
  42. >>> When(account_type=Client.GOLD, then='name')
  43. >>> When(account_type=Client.GOLD, then=F('name'))
  44. >>> # You can use field lookups in the condition
  45. >>> from datetime import date
  46. >>> When(registered_on__gt=date(2014, 1, 1),
  47. ... registered_on__lt=date(2015, 1, 1),
  48. ... then='account_type')
  49. >>> # Complex conditions can be created using Q objects
  50. >>> When(Q(name__startswith="John") | Q(name__startswith="Paul"),
  51. ... then='name')
  52. Keep in mind that each of these values can be an expression.
  53. .. note::
  54. Since the ``then`` keyword argument is reserved for the result of the
  55. ``When()``, there is a potential conflict if a
  56. :class:`~django.db.models.Model` has a field named ``then``. This can be
  57. resolved in two ways::
  58. >>> When(then__exact=0, then=1)
  59. >>> When(Q(then=0), then=1)
  60. ``Case``
  61. --------
  62. .. class:: Case(*cases, **extra)
  63. A ``Case()`` expression is like the :keyword:`if` ... :keyword:`elif` ...
  64. :keyword:`else` statement in ``Python``. Each ``condition`` in the provided
  65. ``When()`` objects is evaluated in order, until one evaluates to a
  66. truthful value. The ``result`` expression from the matching ``When()`` object
  67. is returned.
  68. A simple example::
  69. >>>
  70. >>> from datetime import date, timedelta
  71. >>> from django.db.models import CharField, Case, Value, When
  72. >>> Client.objects.create(
  73. ... name='Jane Doe',
  74. ... account_type=Client.REGULAR,
  75. ... registered_on=date.today() - timedelta(days=36))
  76. >>> Client.objects.create(
  77. ... name='James Smith',
  78. ... account_type=Client.GOLD,
  79. ... registered_on=date.today() - timedelta(days=5))
  80. >>> Client.objects.create(
  81. ... name='Jack Black',
  82. ... account_type=Client.PLATINUM,
  83. ... registered_on=date.today() - timedelta(days=10 * 365))
  84. >>> # Get the discount for each Client based on the account type
  85. >>> Client.objects.annotate(
  86. ... discount=Case(
  87. ... When(account_type=Client.GOLD, then=Value('5%')),
  88. ... When(account_type=Client.PLATINUM, then=Value('10%')),
  89. ... default=Value('0%'),
  90. ... output_field=CharField(),
  91. ... ),
  92. ... ).values_list('name', 'discount')
  93. [('Jane Doe', '0%'), ('James Smith', '5%'), ('Jack Black', '10%')]
  94. ``Case()`` accepts any number of ``When()`` objects as individual arguments.
  95. Other options are provided using keyword arguments. If none of the conditions
  96. evaluate to ``TRUE``, then the expression given with the ``default`` keyword
  97. argument is returned. If a ``default`` argument isn't provided, ``None`` is
  98. used.
  99. If we wanted to change our previous query to get the discount based on how long
  100. the ``Client`` has been with us, we could do so using lookups::
  101. >>> a_month_ago = date.today() - timedelta(days=30)
  102. >>> a_year_ago = date.today() - timedelta(days=365)
  103. >>> # Get the discount for each Client based on the registration date
  104. >>> Client.objects.annotate(
  105. ... discount=Case(
  106. ... When(registered_on__lte=a_year_ago, then=Value('10%')),
  107. ... When(registered_on__lte=a_month_ago, then=Value('5%')),
  108. ... default=Value('0%'),
  109. ... output_field=CharField(),
  110. ... )
  111. ... ).values_list('name', 'discount')
  112. [('Jane Doe', '5%'), ('James Smith', '0%'), ('Jack Black', '10%')]
  113. .. note::
  114. Remember that the conditions are evaluated in order, so in the above
  115. example we get the correct result even though the second condition matches
  116. both Jane Doe and Jack Black. This works just like an :keyword:`if` ...
  117. :keyword:`elif` ... :keyword:`else` statement in ``Python``.
  118. ``Case()`` also works in a ``filter()`` clause. For example, to find gold
  119. clients that registered more than a month ago and platinum clients that
  120. registered more than a year ago::
  121. >>> a_month_ago = date.today() - timedelta(days=30)
  122. >>> a_year_ago = date.today() - timedelta(days=365)
  123. >>> Client.objects.filter(
  124. ... registered_on__lte=Case(
  125. ... When(account_type=Client.GOLD, then=a_month_ago),
  126. ... When(account_type=Client.PLATINUM, then=a_year_ago),
  127. ... ),
  128. ... ).values_list('name', 'account_type')
  129. [('Jack Black', 'P')]
  130. Advanced queries
  131. ================
  132. Conditional expressions can be used in annotations, aggregations, lookups, and
  133. updates. They can also be combined and nested with other expressions. This
  134. allows you to make powerful conditional queries.
  135. Conditional update
  136. ------------------
  137. Let's say we want to change the ``account_type`` for our clients to match
  138. their registration dates. We can do this using a conditional expression and the
  139. :meth:`~django.db.models.query.QuerySet.update` method::
  140. >>> a_month_ago = date.today() - timedelta(days=30)
  141. >>> a_year_ago = date.today() - timedelta(days=365)
  142. >>> # Update the account_type for each Client from the registration date
  143. >>> Client.objects.update(
  144. ... account_type=Case(
  145. ... When(registered_on__lte=a_year_ago,
  146. ... then=Value(Client.PLATINUM)),
  147. ... When(registered_on__lte=a_month_ago,
  148. ... then=Value(Client.GOLD)),
  149. ... default=Value(Client.REGULAR)
  150. ... ),
  151. ... )
  152. >>> Client.objects.values_list('name', 'account_type')
  153. [('Jane Doe', 'G'), ('James Smith', 'R'), ('Jack Black', 'P')]
  154. Conditional aggregation
  155. -----------------------
  156. What if we want to find out how many clients there are for each
  157. ``account_type``? We can nest conditional expression within
  158. :ref:`aggregate functions <aggregation-functions>` to achieve this::
  159. >>> # Create some more Clients first so we can have something to count
  160. >>> Client.objects.create(
  161. ... name='Jean Grey',
  162. ... account_type=Client.REGULAR,
  163. ... registered_on=date.today())
  164. >>> Client.objects.create(
  165. ... name='James Bond',
  166. ... account_type=Client.PLATINUM,
  167. ... registered_on=date.today())
  168. >>> Client.objects.create(
  169. ... name='Jane Porter',
  170. ... account_type=Client.PLATINUM,
  171. ... registered_on=date.today())
  172. >>> # Get counts for each value of account_type
  173. >>> from django.db.models import IntegerField, Sum
  174. >>> Client.objects.aggregate(
  175. ... regular=Sum(
  176. ... Case(When(account_type=Client.REGULAR, then=1),
  177. ... output_field=IntegerField())
  178. ... ),
  179. ... gold=Sum(
  180. ... Case(When(account_type=Client.GOLD, then=1),
  181. ... output_field=IntegerField())
  182. ... ),
  183. ... platinum=Sum(
  184. ... Case(When(account_type=Client.PLATINUM, then=1),
  185. ... output_field=IntegerField())
  186. ... )
  187. ... )
  188. {'regular': 2, 'gold': 1, 'platinum': 3}