From f2026ca5e29273771f4dba75ca99b8dd5812e047 Mon Sep 17 00:00:00 2001 From: Adnan Umer Date: Thu, 19 Apr 2018 15:09:54 +0500 Subject: [PATCH] Fixed #29337 -- Added __len__() & __bool__() to RawQuerySet. --- django/db/models/query.py | 8 ++++++++ docs/topics/db/sql.txt | 8 -------- tests/raw_query/tests.py | 8 ++++++++ 3 files changed, 16 insertions(+), 8 deletions(-) diff --git a/django/db/models/query.py b/django/db/models/query.py index e1f3ce8adf..f16af1e91d 100644 --- a/django/db/models/query.py +++ b/django/db/models/query.py @@ -1293,6 +1293,14 @@ class RawQuerySet: if self._result_cache is None: self._result_cache = list(self.iterator()) + def __len__(self): + self._fetch_all() + return len(self._result_cache) + + def __bool__(self): + self._fetch_all() + return bool(self._result_cache) + def __iter__(self): self._fetch_all() return iter(self._result_cache) diff --git a/docs/topics/db/sql.txt b/docs/topics/db/sql.txt index cff628011e..39a54e4239 100644 --- a/docs/topics/db/sql.txt +++ b/docs/topics/db/sql.txt @@ -85,14 +85,6 @@ options that make it very powerful. both rows will match. To prevent this, perform the correct typecasting before using the value in a query. -.. warning:: - - While a ``RawQuerySet`` instance can be iterated over like a normal - :class:`~django.db.models.query.QuerySet`, ``RawQuerySet`` doesn't - implement all methods you can use with ``QuerySet``. For example, - ``__bool__()`` and ``__len__()`` are not defined in ``RawQuerySet``, and - thus all ``RawQuerySet`` instances are considered ``True``. - Mapping query fields to model fields ------------------------------------ diff --git a/tests/raw_query/tests.py b/tests/raw_query/tests.py index 1f0d0c363f..703a6b311e 100644 --- a/tests/raw_query/tests.py +++ b/tests/raw_query/tests.py @@ -330,3 +330,11 @@ class RawQueryTests(TestCase): books = Book.objects.raw('SELECT * FROM raw_query_book') list(books.iterator()) list(books.iterator()) + + def test_bool(self): + self.assertIs(bool(Book.objects.raw('SELECT * FROM raw_query_book')), True) + self.assertIs(bool(Book.objects.raw('SELECT * FROM raw_query_book WHERE id = 0')), False) + + def test_len(self): + self.assertEqual(len(Book.objects.raw('SELECT * FROM raw_query_book')), 4) + self.assertEqual(len(Book.objects.raw('SELECT * FROM raw_query_book WHERE id = 0')), 0)