Junior — Middle
How is data paginated in Django to display large collections of information?
sobes.tech AI
Answer from AI
In Django, the Paginator class from the django.core.paginator module is used for splitting data into pages. It allows you to divide a large dataset (for example, a QuerySet) into fixed-size pages and conveniently access objects for a specific page.
Example of usage:
from django.core.paginator import Paginator
items = MyModel.objects.all() # large QuerySet
paginator = Paginator(items, 10) # 10 objects per page
page_number = request.GET.get('page') # page number from request
page_obj = paginator.get_page(page_number)
# In the template, you can use page_obj to display items and navigation
Thus, Paginator handles the logic of calculating the number of pages, validating the page number, and provides a convenient interface for accessing the data of the current page.