#35733: Page.__len__ could skip a query if self.paginator.count == 0
-------------------------------------+-------------------------------------
               Reporter:  Jacob      |          Owner:  Jacob Walls
  Walls                              |
                   Type:             |         Status:  assigned
  Cleanup/optimization               |
              Component:  Core       |        Version:  dev
  (Other)                            |
               Severity:  Normal     |       Keywords:
           Triage Stage:             |      Has patch:  0
  Unreviewed                         |
    Needs documentation:  0          |    Needs tests:  0
Patch needs improvement:  0          |  Easy pickings:  0
                  UI/UX:  0          |
-------------------------------------+-------------------------------------
 With code like this,
 {{{
 paginator = Paginator(unevaluated_queryset, 25)
 page = paginator.get_page(1)  # causes count query via validate_number()
 if not page:  # causes select query
     return {}
 }}}
 I get an additional query versus:
 {{{
 paginator = Paginator(unevaluated_queryset, 25)
 if not paginator.count:  # causes count query
     return {}
 }}}

 ----
 In the case of no data, the second SELECT query is unnecessary if we
 already know the paginator is empty. Since `paginator.count` is cached,
 would it be worth optimizing out this additional query? Otherwise, you
 have to dig into the internals to discover that the two examples above do
 not perform equivalently.

 {{{#!diff
 diff --git a/django/core/paginator.py b/django/core/paginator.py
 index 7b3189cc8b..334166636d 100644
 --- a/django/core/paginator.py
 +++ b/django/core/paginator.py
 @@ -188,6 +188,8 @@ class Page(collections.abc.Sequence):
          return "<Page %s of %s>" % (self.number,
 self.paginator.num_pages)

      def __len__(self):
 +        if self.paginator.count == 0:
 +            return 0
          return len(self.object_list)

      def __getitem__(self, index):
 }}}
-- 
Ticket URL: <https://code.djangoproject.com/ticket/35733>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.

-- 
You received this message because you are subscribed to the Google Groups 
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-updates/01070191c25fb01e-b162757c-9806-4249-a3d1-0e9bacd9510b-000000%40eu-central-1.amazonses.com.

Reply via email to