Python django.db.models.query.EmptyQuerySet() Examples

The following are 20 code examples of django.db.models.query.EmptyQuerySet(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.db.models.query , or try the search function .
Example #1
Source File: test_querysetsequence.py    From django-querysetsequence with ISC License 6 votes vote down vote up
def test_and(self):
        """ANDing with a QuerySet applies the and to each QuerySet and removes ones of differing types."""
        # ANDing with a different type of QuerySet ends up with an EmptyQuerySet.
        with self.assertNumQueries(0):
            combined = self.all & BlogPost.objects.all()
        self.assertIsInstance(combined, EmptyQuerySet)

        # ANDing with a QuerySet of a type in the QuerySetSequence applies the
        # AND to that QuerySet.
        with self.assertNumQueries(0):
            combined = self.all & Book.objects.filter(pages__lt=15)
        self.assertIsInstance(combined, QuerySetSequence)
        self.assertEqual(len(combined._querysets), 1)
        with self.assertNumQueries(1):
            data = [it.title for it in combined.iterator()]
        self.assertEqual(data, ['Fiction']) 
Example #2
Source File: __init__.py    From django-querysetsequence with ISC License 6 votes vote down vote up
def __and__(self, other):
        # If the other QuerySet is an EmptyQuerySet, this is a no-op.
        if isinstance(other, EmptyQuerySet):
            return other
        combined = self._clone()

        querysets = []
        for qs in combined._querysets:
            # Only QuerySets of the same type can have any overlap.
            if issubclass(qs.model, other.model):
                querysets.append(qs & other)

        # If none are left, we're left with an EmptyQuerySet.
        if not querysets:
            return other.none()

        combined._set_querysets(querysets)
        return combined 
Example #3
Source File: __init__.py    From django-querysetsequence with ISC License 5 votes vote down vote up
def none(self):
        # This is a bit odd, but use the first QuerySet to properly return an
        # that is an instance of EmptyQuerySet.
        return self._querysets[0].none() 
Example #4
Source File: test_models.py    From connect with MIT License 5 votes vote down vote up
def test_coords_no_targets(self, mock):
        """If no coordinates are returned return an empty QuerySet"""
        mock.return_value = None

        groups = Group.objects.location_search('None, None')

        mock.assert_called_once_with('None, None')

        self.assertIsInstance(groups, EmptyQuerySet) 
Example #5
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_emptyqs_customqs(self):
        # A hacky test for custom QuerySet subclass - refs #17271
        Article.objects.create(headline='foo', pub_date=datetime.now())

        class CustomQuerySet(QuerySet):
            def do_something(self):
                return 'did something'

        qs = Article.objects.all()
        qs.__class__ = CustomQuerySet
        qs = qs.none()
        with self.assertNumQueries(0):
            self.assertEqual(len(qs), 0)
            self.assertIsInstance(qs, EmptyQuerySet)
            self.assertEqual(qs.do_something(), 'did something') 
Example #6
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_emptyqs_values(self):
        # test for #15959
        Article.objects.create(headline='foo', pub_date=datetime.now())
        with self.assertNumQueries(0):
            qs = Article.objects.none().values_list('pk')
            self.assertIsInstance(qs, EmptyQuerySet)
            self.assertEqual(len(qs), 0) 
Example #7
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_model_multiple_choice_required_false(self):
        f = forms.ModelMultipleChoiceField(Category.objects.all(), required=False)
        self.assertIsInstance(f.clean([]), EmptyQuerySet)
        self.assertIsInstance(f.clean(()), EmptyQuerySet)
        with self.assertRaises(ValidationError):
            f.clean(['0'])
        with self.assertRaises(ValidationError):
            f.clean([str(self.c3.id), '0'])
        with self.assertRaises(ValidationError):
            f.clean([str(self.c1.id), '0'])

        # queryset can be changed after the field is created.
        f.queryset = Category.objects.exclude(name='Third')
        self.assertEqual(list(f.choices), [
            (self.c1.pk, 'Entertainment'),
            (self.c2.pk, "It's a test")])
        self.assertQuerysetEqual(f.clean([self.c2.id]), ["It's a test"])
        with self.assertRaises(ValidationError):
            f.clean([self.c3.id])
        with self.assertRaises(ValidationError):
            f.clean([str(self.c2.id), str(self.c3.id)])

        f.queryset = Category.objects.all()
        f.label_from_instance = lambda obj: "multicategory " + str(obj)
        self.assertEqual(list(f.choices), [
            (self.c1.pk, 'multicategory Entertainment'),
            (self.c2.pk, "multicategory It's a test"),
            (self.c3.pk, 'multicategory Third')]) 
Example #8
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_emptyqs_customqs(self):
        # A hacky test for custom QuerySet subclass - refs #17271
        Article.objects.create(headline='foo', pub_date=datetime.now())

        class CustomQuerySet(QuerySet):
            def do_something(self):
                return 'did something'

        qs = Article.objects.all()
        qs.__class__ = CustomQuerySet
        qs = qs.none()
        with self.assertNumQueries(0):
            self.assertEqual(len(qs), 0)
            self.assertIsInstance(qs, EmptyQuerySet)
            self.assertEqual(qs.do_something(), 'did something') 
Example #9
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_emptyqs_values(self):
        # test for #15959
        Article.objects.create(headline='foo', pub_date=datetime.now())
        with self.assertNumQueries(0):
            qs = Article.objects.none().values_list('pk')
            self.assertIsInstance(qs, EmptyQuerySet)
            self.assertEqual(len(qs), 0) 
Example #10
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_emptyqs(self):
        msg = "EmptyQuerySet can't be instantiated"
        with self.assertRaisesMessage(TypeError, msg):
            EmptyQuerySet()
        self.assertIsInstance(Article.objects.none(), EmptyQuerySet)
        self.assertNotIsInstance('', EmptyQuerySet) 
Example #11
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_model_multiple_choice_required_false(self):
        f = forms.ModelMultipleChoiceField(Category.objects.all(), required=False)
        self.assertIsInstance(f.clean([]), EmptyQuerySet)
        self.assertIsInstance(f.clean(()), EmptyQuerySet)
        with self.assertRaises(ValidationError):
            f.clean(['0'])
        with self.assertRaises(ValidationError):
            f.clean([str(self.c3.id), '0'])
        with self.assertRaises(ValidationError):
            f.clean([str(self.c1.id), '0'])

        # queryset can be changed after the field is created.
        f.queryset = Category.objects.exclude(name='Third')
        self.assertEqual(list(f.choices), [
            (self.c1.pk, 'Entertainment'),
            (self.c2.pk, "It's a test")])
        self.assertQuerysetEqual(f.clean([self.c2.id]), ["It's a test"])
        with self.assertRaises(ValidationError):
            f.clean([self.c3.id])
        with self.assertRaises(ValidationError):
            f.clean([str(self.c2.id), str(self.c3.id)])

        f.queryset = Category.objects.all()
        f.label_from_instance = lambda obj: "multicategory " + str(obj)
        self.assertEqual(list(f.choices), [
            (self.c1.pk, 'multicategory Entertainment'),
            (self.c2.pk, "multicategory It's a test"),
            (self.c3.pk, 'multicategory Third')]) 
Example #12
Source File: manager.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def get_empty_query_set(self):
        return EmptyQuerySet(self.model, using=self._db) 
Example #13
Source File: querysets.py    From FIR with GNU General Public License v3.0 5 votes vote down vote up
def filter(self, *args, **kwargs):
        """
        Returns a new QuerySetSequence or instance with the args ANDed to the
        existing set.

        QuerySetSequence is simplified thus result actually can be one of:
        QuerySetSequence, QuerySet, EmptyQuerySet.
        """
        return self._filter_or_exclude(False, *args, **kwargs) 
Example #14
Source File: __init__.py    From django-querysetsequence with ISC License 5 votes vote down vote up
def __or__(self, other):
        # If the other QuerySet is an EmptyQuerySet, this is a no-op.
        if isinstance(other, EmptyQuerySet):
            return self
        combined = self._clone()

        # If the other instance is a QuerySetSequence, combine the QuerySets.
        if isinstance(other, QuerySetSequence):
            combined._set_querysets(self._querysets + other._querysets)

        elif isinstance(other, QuerySet):
            combined._set_querysets(self._querysets + [other])

        return combined 
Example #15
Source File: test_querysetsequence.py    From django-querysetsequence with ISC License 5 votes vote down vote up
def test_none(self):
        """
        Ensure an instance of EmptyQuerySet is returned and has no results (and
        doesn't perform queries).
        """
        with self.assertNumQueries(0):
            qss = self.all.none()
            data = list(qss)

        # This returns an EmptyQuerySet.
        self.assertIsInstance(qss, EmptyQuerySet)

        # Should have no data.
        self.assertEqual(data, []) 
Example #16
Source File: test_querysetsequence.py    From django-querysetsequence with ISC License 5 votes vote down vote up
def test_empty_or(self):
        """An empty QuerySetSequence can be ORed with a QuerySet, but returns an EmptyQuerySet."""
        combined = self.empty | BlogPost.objects.all()
        self.assertIsInstance(combined, QuerySetSequence)
        self.assertEqual(len(combined._querysets), 1)

        with self.assertNumQueries(1):
            data = [it.title for it in combined.iterator()]
        self.assertEqual(data, ['Post']) 
Example #17
Source File: test_querysetsequence.py    From django-querysetsequence with ISC License 5 votes vote down vote up
def test_empty_and(self):
        """An empty QuerySetSequence can be ANDed with a QuerySet, but returns an EmptyQuerySet."""
        combined = self.empty & BlogPost.objects.all()
        self.assertIsInstance(combined, EmptyQuerySet)
        self.assertEqual(list(combined), []) 
Example #18
Source File: test_querysetsequence.py    From django-querysetsequence with ISC License 5 votes vote down vote up
def test_and_identity(self):
        """ANDing with an EmptyQuerySet returns an EmptyQuerySet."""
        with self.assertNumQueries(0):
            combined = self.all & BlogPost.objects.none()
        self.assertIsInstance(combined, EmptyQuerySet) 
Example #19
Source File: querysets.py    From FIR with GNU General Public License v3.0 5 votes vote down vote up
def _simplify(self, qss=None):
        '''
        Returns QuerySetSequence, QuerySet or EmptyQuerySet depending on the
        contents of items, i.e. at least two non empty QuerySets, exactly one
        non empty QuerySet and all empty QuerySets respectively.

        Does not modify original QuerySetSequence.
        '''
        not_empty_qss = filter(None, qss if qss else self.iables)
        if not len(not_empty_qss):
            return EmptyQuerySet()
        if len(not_empty_qss) == 1:
            return not_empty_qss[0]
        return QuerySetSequence(*not_empty_qss) 
Example #20
Source File: querysets.py    From FIR with GNU General Public License v3.0 5 votes vote down vote up
def exclude(self, *args, **kwargs):
        """
        Returns a new QuerySetSequence instance with NOT (args) ANDed to the
        existing set.

        QuerySetSequence is simplified thus result actually can be one of:
        QuerySetSequence, QuerySet, EmptyQuerySet.
        """
        return self._filter_or_exclude(True, *args, **kwargs)