conditional-expressions.txt 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  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. Advanced queries
  119. ================
  120. Conditional expressions can be used in annotations, aggregations, lookups, and
  121. updates. They can also be combined and nested with other expressions. This
  122. allows you to make powerful conditional queries.
  123. Conditional update
  124. ------------------
  125. Let's say we want to change the ``account_type`` for our clients to match
  126. their registration dates. We can do this using a conditional expression and the
  127. :meth:`~django.db.models.query.QuerySet.update` method::
  128. >>> a_month_ago = date.today() - timedelta(days=30)
  129. >>> a_year_ago = date.today() - timedelta(days=365)
  130. >>> # Update the account_type for each Client from the registration date
  131. >>> Client.objects.update(
  132. ... account_type=Case(
  133. ... When(registered_on__lte=a_year_ago,
  134. ... then=Value(Client.PLATINUM)),
  135. ... When(registered_on__lte=a_month_ago,
  136. ... then=Value(Client.GOLD)),
  137. ... default=Value(Client.REGULAR)
  138. ... ),
  139. ... )
  140. >>> Client.objects.values_list('name', 'account_type')
  141. [('Jane Doe', 'G'), ('James Smith', 'R'), ('Jack Black', 'P')]
  142. Conditional aggregation
  143. -----------------------
  144. What if we want to find out how many clients there are for each
  145. ``account_type``? We can nest conditional expression within
  146. :ref:`aggregate functions <aggregation-functions>` to achieve this::
  147. >>> # Create some more Clients first so we can have something to count
  148. >>> Client.objects.create(
  149. ... name='Jean Grey',
  150. ... account_type=Client.REGULAR,
  151. ... registered_on=date.today())
  152. >>> Client.objects.create(
  153. ... name='James Bond',
  154. ... account_type=Client.PLATINUM,
  155. ... registered_on=date.today())
  156. >>> Client.objects.create(
  157. ... name='Jane Porter',
  158. ... account_type=Client.PLATINUM,
  159. ... registered_on=date.today())
  160. >>> # Get counts for each value of account_type
  161. >>> from django.db.models import IntegerField, Sum
  162. >>> Client.objects.aggregate(
  163. ... regular=Sum(
  164. ... Case(When(account_type=Client.REGULAR, then=1),
  165. ... output_field=IntegerField())
  166. ... ),
  167. ... gold=Sum(
  168. ... Case(When(account_type=Client.GOLD, then=1),
  169. ... output_field=IntegerField())
  170. ... ),
  171. ... platinum=Sum(
  172. ... Case(When(account_type=Client.PLATINUM, then=1),
  173. ... output_field=IntegerField())
  174. ... )
  175. ... )
  176. {'regular': 2, 'gold': 1, 'platinum': 3}