Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Fixed #6748 -- When printing the repr() of querysets, don't load or d…

…isplay

more than 20 objects.

This means that accidentally executing HugeStoryArchive.objects.all() at the
interactive prompt (or in the debug template) won't try to load all 4,233,010
stories into memory and print them out. That would previously cause resource
starvation and other "interesting" crashes.

If you really, really want the previous behaviour (e.g. in a doctest that
prints more than 20 items), display "list(qs)" instead of just "qs".


git-svn-id: http://code.djangoproject.com/svn/django/trunk@9202 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information...
commit 44f228fd61e5f45dbdfa465291319dfd5dd66393 1 parent 268ef59
Malcolm Tredinnick authored October 08, 2008
8  django/db/models/query.py
@@ -15,6 +15,9 @@
15 15
 CHUNK_SIZE = 100
16 16
 ITER_CHUNK_SIZE = CHUNK_SIZE
17 17
 
  18
+# The maximum number of items to display in a QuerySet.__repr__
  19
+REPR_OUTPUT_SIZE = 20
  20
+
18 21
 # Pull into this namespace for backwards compatibility.
19 22
 EmptyResultSet = sql.EmptyResultSet
20 23
 
@@ -141,7 +144,10 @@ def __getstate__(self):
141 144
         return obj_dict
142 145
 
143 146
     def __repr__(self):
144  
-        return repr(list(self))
  147
+        data = list(self[:REPR_OUTPUT_SIZE + 1])
  148
+        if len(data) > REPR_OUTPUT_SIZE:
  149
+            data[-1] = "...(remaining elements truncated)..."
  150
+        return repr(data)
145 151
 
146 152
     def __len__(self):
147 153
         # Since __len__ is called quite frequently (for example, as part of
2  tests/regressiontests/queries/models.py
@@ -556,7 +556,7 @@ def __unicode__(self):
556 556
 # automatically. Item normally requires a join with Note to do the default
557 557
 # ordering, but that isn't needed here.
558 558
 >>> qs = Item.objects.order_by('name')
559  
->>> qs
  559
+>>> list(qs)
560 560
 [<Item: four>, <Item: one>, <Item: three>, <Item: two>]
561 561
 >>> len(qs.query.tables)
562 562
 1

0 notes on commit 44f228f

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