Opened 12 years ago

Last modified 12 years ago

#18463 closed Bug

Using len() in Paginator object can raise an error — at Version 1

Reported by: renato@… Owned by: Claude Paroz
Component: Core (Other) Version: dev
Severity: Normal Keywords:
Cc: Triage Stage: Accepted
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description (last modified by Claude Paroz)

I'm getting the following error if I try to run a piece of code through my views.py:

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/home/mp/webapps/django/rep/app/views.py", line 331, in search_species
    print len(recs)
  File "/home/mp/webapps/django/lib/python2.7/django/core/paginator.py", line 88, in __len__
    return len(self.object_list)
  File "/home/mp/webapps/django/lib/python2.7/django/db/models/query.py", line 87, in __len__
    self._result_cache = list(self.iterator())
  File "/home/mp/webapps/django/lib/python2.7/django/db/models/query.py", line 284, in iterator
    model_cls = deferred_class_factory(self.model, skip)
  File "/home/mp/webapps/django/lib/python2.7/django/db/models/query_utils.py", line 180, in deferred_class_factory
    return type(name, (model,), overrides)
TypeError: type() argument 1 must be string, not unicode

Strangely, if I run a similar code directly in the Django shell, everything goes well. The code looks like this:

from app.models import MyClass
qs = MyClass.objects.all()
from django.core.paginator import Paginator
paginator = Paginator(qs, 25)
recs = paginator.page(1)
print len(recs)

So you have to run this code through a method in views.py to get a crash in the last line.

I'm afraid I have no idea of what's going on and how to properly fix this, but if I change the offending line from the traceback by forcing str() in the name parameter it works:

return type(str(name), (model,), overrides)

Change History (1)

comment:1 by Claude Paroz, 12 years ago

Description: modified (diff)
Owner: changed from nobody to Claude Paroz
Status: newassigned
Triage Stage: UnreviewedAccepted

This bug is only triggered when the model name in deferred_class_factory is truncated (> 80 chars) and then a Unicode string is returned. Calling str() seems a good solution.

Note: See TracTickets for help on using tickets.
Back to Top