mengu on web programming.

Pagination With Web2Py

I was developing a [web2py](http://www.web2py.com) blog application to be a teaching one for the web2py beginners. After completing many parts, the next part was pagination. I have thought on how to do it. The normal select statement on web2py is as the following statement: db(db.post.id > 0).select() If you want to limit a select then you should use the following: db(db.post.id > 0).select(limitby(0,10)) With this statement you select the first 10 posts in your database. So 10 is your LIMIT and 0 is your OFFSET. If you try to do set 5 as OFFSET and 10 AS LIMIT, you will be disappointed because it won't work as you expect because of the 2846th line in sql.py. You will see the following code: sql_o += ' LIMIT %i OFFSET %i' % (lmax - lmin, lmin) This line makes your query LIMIT 5 OFFSET 5. The issue here is that you should make it like (lmax, lmin) and it will work as expected. Here is the pagination part: perpage = 3 totalposts = db(db.post.id > 0).count() totalpages = totalposts / perpage if totalposts > perpage and totalpages == 1 and totalpages * perpage != totalposts: totalpages = 2 page = int(request.vars.page) if request.vars.page else 1 limit = int(page - 1) * perpage posts = db(db.post.id > 0).select(orderby=~db.post.id, limitby=(limit, perpage)) And in your view you should use the following codes: {{ if totalpages > 1:}}
{{ for i in range(1, totalpages+1): }}
{{ if postpage == i: }} {{=i}} {{ else: }}{{=i}}{{ pass }}
{{ pass }}
{{ pass }}
Check my latest project compector.com where you can post references about your former employers and see what others have said about the future employers. Sign up now and post a reference and share it on twitter or facebook.

Comments

niphlod said on 27/08/2010 02:08 AM
hi mengu, your analysis is correct, but implementation is wrong. ref http://web2py.com/book/default/chapter/12#Pagination Say you want 3 pages of blog posts, you want 5 post per page. To extract data from the database, you need to issue: page 1: `limit 5 offset 0` page 2: `limit 5 offset 5` page 3: `limit 5 offset 10` now, if limit is (lmax - lmin) and offset is lmin, you need to have: page 1: `lmax 5 lmin 0` => `perpage 5 limit 0` page 2: `lmax 10 lmin 5` => `perpage 10 limit 5` page 3: `lmax 15 lmin 10` => `perpage 15 limit 10` to fix the behaviour in your code, perpage needs to be multiplied per page `perpage = perpage * page` sorry to be late, but it appears that for "web2py pagination" you are the 1st result on google ^_^

Mengu Kagan said on 28/08/2010 18:01 PM
hello niphlod, thank you for the information. let me just give this a try and then i will update the post. :) it also appears that i'm the first result for web.py pagination too. :)

Leave a Response

No HTML allowed. You can use markdown.
Name*:
E-Mail* (not published):
Web site:
Response: