Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to do pagination using mongoengine?

i have a question about pagination using mongodb and mongoengine. i have a table which will have millions of records in future. and i am doing paging like this.

well i am not sure this is correct approach

    list = Books.objects.all()
    paginator = DiggPaginator(list, 20, body = 10, tail = 2)

here i open whole table and then do the pagination and we on for next page again above code runs and brings the 2nd or any page.

is this correct approach or there are any better ways to do this.

like image 517
user493550 Avatar asked Nov 22 '12 05:11

user493550


3 Answers

You can use skip and limit from QuerySet to achieve pagination.
For example if you want to show the second page with a limitation of 10 items per page, you can do like this:

page_nb = 2 
items_per_page = 10 

offset = (page_nb - 1) * items_per_page

list = Books.objects.skip( offset ).limit( items_per_page )
like image 70
Eric Avatar answered Oct 11 '22 15:10

Eric


You can use array-slicing syntax as well which is a bit more decent and readable :

begin = (page - 1) * page_size # offset
end = offset + page_size
list = Books.objects[begin:end]()
like image 41
Code_Worm Avatar answered Oct 11 '22 14:10

Code_Worm


The flask-mongoengine plugin has an example of a paginator you could adapt to follow the digg paginator.

like image 44
Ross Avatar answered Oct 11 '22 15:10

Ross