Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Fixed #18087 -- Prevented date-based generic views from loading entir…

…e tables in memory when pagination is enabled.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@17893 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information...
commit 28e5b665189548557993b522e3bd7adeed3f62ea 1 parent 916d705
Aymeric Augustin authored April 10, 2012
13  django/views/generic/dates.py
@@ -190,14 +190,19 @@ def get_dated_queryset(self, **lookup):
190 190
         date_field = self.get_date_field()
191 191
         allow_future = self.get_allow_future()
192 192
         allow_empty = self.get_allow_empty()
  193
+        paginate_by = self.get_paginate_by(qs)
193 194
 
194 195
         if not allow_future:
195 196
             qs = qs.filter(**{'%s__lte' % date_field: timezone.now()})
196 197
 
197  
-        if not allow_empty and not qs:
198  
-            raise Http404(_(u"No %(verbose_name_plural)s available") % {
199  
-                    'verbose_name_plural': force_unicode(qs.model._meta.verbose_name_plural)
200  
-            })
  198
+        if not allow_empty:
  199
+            # When pagination is enabled, it's better to do a cheap query
  200
+            # than to load the unpaginated queryset in memory.
  201
+            is_empty = not bool(qs) if paginate_by is None else not qs.exists()
  202
+            if is_empty:
  203
+                raise Http404(_(u"No %(verbose_name_plural)s available") % {
  204
+                        'verbose_name_plural': force_unicode(qs.model._meta.verbose_name_plural)
  205
+                })
201 206
 
202 207
         return qs
203 208
 
9  tests/regressiontests/generic_views/dates.py
@@ -78,6 +78,15 @@ def test_paginated_archive_view(self):
78 78
         self.assertEqual(res.context['page_obj'].number, 2)
79 79
         self.assertEqual(list(res.context['latest']), list(Book.objects.all()[10:20]))
80 80
 
  81
+    def test_paginated_archive_view_does_not_load_entire_table(self):
  82
+        # Regression test for #18087
  83
+        self._make_books(20, base_date=datetime.date.today())
  84
+        # 1 query for years list + 1 query for books
  85
+        with self.assertNumQueries(2):
  86
+            self.client.get('/dates/books/')
  87
+        # same as above + 1 query to test if books exist
  88
+        with self.assertNumQueries(3):
  89
+            self.client.get('/dates/books/paginated/')
81 90
 
82 91
 class YearArchiveViewTests(TestCase):
83 92
     fixtures = ['generic-views-test-data.json']

0 notes on commit 28e5b66

Please sign in to comment.
Something went wrong with that request. Please try again.