summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJonatas CD <jonatas.cd@gmail.com>2016-11-15 12:54:45 +0100
committerTim Graham <timograham@gmail.com>2016-11-17 12:39:35 -0500
commitb28c6ca7631e13ea29490bf51a367ab10198c74c (patch)
tree58abe6c8a184469573c717f46717440dfe7b452a
parent721f0ca85c68929354b3ea20cdc61cb671652487 (diff)
Fixed #27482 -- Doc'd an example of Case() in QuerySet.filter().
-rw-r--r--docs/ref/models/conditional-expressions.txt14
-rw-r--r--tests/expressions_case/tests.py14
2 files changed, 28 insertions, 0 deletions
diff --git a/docs/ref/models/conditional-expressions.txt b/docs/ref/models/conditional-expressions.txt
index da2b4618f3..4331d1185e 100644
--- a/docs/ref/models/conditional-expressions.txt
+++ b/docs/ref/models/conditional-expressions.txt
@@ -141,6 +141,20 @@ the ``Client`` has been with us, we could do so using lookups::
both Jane Doe and Jack Black. This works just like an :keyword:`if` ...
:keyword:`elif` ... :keyword:`else` statement in ``Python``.
+``Case()`` also works in a ``filter()`` clause. For example, to find gold
+clients that registered more than a month ago and platinum clients that
+registered more than a year ago::
+
+ >>> a_month_ago = date.today() - timedelta(days=30)
+ >>> a_year_ago = date.today() - timedelta(days=365)
+ >>> Client.objects.filter(
+ ... registered_on__lte=Case(
+ ... When(account_type=Client.GOLD, then=a_month_ago),
+ ... When(account_type=Client.PLATINUM, then=a_year_ago),
+ ... ),
+ ... ).values_list('name', 'account_type')
+ [('Jack Black', 'P')]
+
Advanced queries
================
diff --git a/tests/expressions_case/tests.py b/tests/expressions_case/tests.py
index c3b754fcae..91806c2764 100644
--- a/tests/expressions_case/tests.py
+++ b/tests/expressions_case/tests.py
@@ -1289,3 +1289,17 @@ class CaseDocumentationExamples(TestCase):
),
{'regular': 2, 'gold': 1, 'platinum': 3}
)
+
+ def test_filter_example(self):
+ a_month_ago = date.today() - timedelta(days=30)
+ a_year_ago = date.today() - timedelta(days=365)
+ self.assertQuerysetEqual(
+ Client.objects.filter(
+ registered_on__lte=Case(
+ When(account_type=Client.GOLD, then=a_month_ago),
+ When(account_type=Client.PLATINUM, then=a_year_ago),
+ ),
+ ),
+ [('Jack Black', 'P')],
+ transform=attrgetter('name', 'account_type')
+ )