Django pagination

I need to do a real pagination instead of paginating all the data received. An example in the documentation for Django documentation:

def listing(request): contact_list = Contacts.objects.all() paginator = Paginator(contact_list, 25) # Show 25 contacts per page page = request.GET.get('page') try: contacts = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. contacts = paginator.page(1) except EmptyPage: # If page is out of range (eg 9999), deliver last page of results. contacts = paginator.page(paginator.num_pages) return render_to_response('list.html', {"contacts": contacts}) 

This code is a pagination of all deleted records. But there is a problem. Trying to get the whole record takes a lot of time if there are so many records. I need a solution to retrieve records per page from a database.

Is there any other solution for this in Django?

+6
source share
3 answers

You make a false assumption. Django does not retrieve all objects when paginated: it correctly sorts a query that uses LIMIT and COUNT for SQL.

+18
source

View the Paginator class (django / core / paginator.py), it selects only the required pages. In large tables, there is only one problem: if you want to show the common page numbers, you must make an account (*) on the entire table, which can take a lot of time in some databases (i.e. Postgresql, mysql with innodb).

By the way, try using generic views in django, the ListView will be fine.

0
source

A QuerySet is a lazy object. When you assign contact_list = Contacts.objects.all() , Django will NOT get into the database. Until you call methods like count() , filter() , first() , ... or contact_list[1:5] , Django will actually retrieve data from the database. The SQL statements that Django generate will correlate with each method, and this SQL data will be sent to the database.

For example: contact_list[1:5] generate an SQL statement have LIMIT and OFFSET clauses.

In a Paginator the QuerySet class is passed to its constructor

 paginator = Paginator(contact_list, 25) 

When you call paginator.page(page) , the statement is called:

 return self._get_page(self.object_list[bottom:top], number, self) 
0
source

Source: https://habr.com/ru/post/924604/


All Articles