Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django pagination and RawQuerySet

is there a way to paginate a rawqueryset using django's inbuilt pagination? when i cast it to a list , it throws an error in my face ...TypeError: expected string or Unicode object, NoneType found. Is there a way around this?

like image 214
mossplix Avatar asked Mar 01 '11 10:03

mossplix


2 Answers

I managed to achieve it using the following:

paginator = Paginator(files, 12)
paginator._count = len(list(files))

The code in django.core.paginator.py:

  • checks for whether _count is set
  • if not then tries to run .count() which doesn't exist
  • if not then tries plain len

len on a raw_queryset doesn't work but converting the actual paginator object to a list works find for me in Django 1.3

like image 84
Chris Avatar answered Oct 13 '22 02:10

Chris


You can set the attribute count manually for your RawQuerySet object:

items = Item.objects.raw("select * from appitem_item")

def items_count():
    cursor = connection.cursor()
    cursor.execute("select count(*) from appitem_item")
    row = cursor.fetchone()
    return row[0]

items.count = items_count

for @Rockallite

>>> class A():
...    def b(self):
...        print 'from b'
... 
>>> 
>>> (A()).b()
from b
>>> def c():
...    print 'from c'
... 
>>> a = A()
>>> a.b = c
>>> a.b()
from c
like image 20
Andrei Kaigorodov Avatar answered Oct 13 '22 00:10

Andrei Kaigorodov