Browse Source

Refs #27718 -- Doc'd and tested QuerySet.exists() for combined querysets.

Supported since 84c1826ded17b2d74f66717fb745fc36e37949fd.
David-Wobrock 4 years ago
parent
commit
7b42d34646
2 changed files with 28 additions and 5 deletions
  1. 5 5
      docs/ref/models/querysets.txt
  2. 23 0
      tests/queries/test_qs_combinators.py

+ 5 - 5
docs/ref/models/querysets.txt

@@ -917,11 +917,11 @@ resulting ``QuerySet``. For example::
     >>> qs1.union(qs2).order_by('name')
 
 In addition, only ``LIMIT``, ``OFFSET``, ``COUNT(*)``, ``ORDER BY``, and
-specifying columns (i.e. slicing, :meth:`count`, :meth:`order_by`, and
-:meth:`values()`/:meth:`values_list()`) are allowed on the resulting
-``QuerySet``. Further, databases place restrictions on what operations are
-allowed in the combined queries. For example, most databases don't allow
-``LIMIT`` or ``OFFSET`` in the combined queries.
+specifying columns (i.e. slicing, :meth:`count`, :meth:`exists`,
+:meth:`order_by`, and :meth:`values()`/:meth:`values_list()`) are allowed
+on the resulting ``QuerySet``. Further, databases place restrictions on
+what operations are allowed in the combined queries. For example, most
+databases don't allow ``LIMIT`` or ``OFFSET`` in the combined queries.
 
 ``intersection()``
 ~~~~~~~~~~~~~~~~~~

+ 23 - 0
tests/queries/test_qs_combinators.py

@@ -254,6 +254,29 @@ class QuerySetSetOperationTests(TestCase):
         qs2 = Number.objects.filter(num__lte=5)
         self.assertEqual(qs1.intersection(qs2).count(), 1)
 
+    def test_exists_union(self):
+        qs1 = Number.objects.filter(num__gte=5)
+        qs2 = Number.objects.filter(num__lte=5)
+        self.assertIs(qs1.union(qs2).exists(), True)
+
+    def test_exists_union_empty_result(self):
+        qs = Number.objects.filter(pk__in=[])
+        self.assertIs(qs.union(qs).exists(), False)
+
+    @skipUnlessDBFeature('supports_select_intersection')
+    def test_exists_intersection(self):
+        qs1 = Number.objects.filter(num__gt=5)
+        qs2 = Number.objects.filter(num__lt=5)
+        self.assertIs(qs1.intersection(qs1).exists(), True)
+        self.assertIs(qs1.intersection(qs2).exists(), False)
+
+    @skipUnlessDBFeature('supports_select_difference')
+    def test_exists_difference(self):
+        qs1 = Number.objects.filter(num__gte=5)
+        qs2 = Number.objects.filter(num__gte=3)
+        self.assertIs(qs1.difference(qs2).exists(), False)
+        self.assertIs(qs2.difference(qs1).exists(), True)
+
     def test_get_union(self):
         qs = Number.objects.filter(num=2)
         self.assertEqual(qs.union(qs).get().num, 2)