| 1 | """ |
| 2 | 20. Object Pagination |
| 3 | |
| 4 | Django provides a framework for paginating a list of objects in a few. |
| 5 | This is often useful for dividing search results or long lists of objects |
| 6 | in to easily readable pages. |
| 7 | |
| 8 | |
| 9 | """ |
| 10 | from django.db import models |
| 11 | |
| 12 | class Article(models.Model): |
| 13 | headline = models.CharField(maxlength=100, default='Default headline') |
| 14 | pub_date = models.DateTimeField() |
| 15 | |
| 16 | def __repr__(self): |
| 17 | return self.headline |
| 18 | |
| 19 | API_TESTS = """ |
| 20 | # prepare a list of objects for pagination |
| 21 | >>> from datetime import datetime |
| 22 | >>> for x in range(1, 10): |
| 23 | ... a = Article(headline='Article %s' % x, pub_date=datetime(2005, 7, 29)) |
| 24 | ... a.save() |
| 25 | |
| 26 | # create a basic paginator, 5 articles per page |
| 27 | >>> from django.core.paginator import ObjectPaginator, InvalidPage |
| 28 | >>> paginator = ObjectPaginator(Article.objects.all(), 5) |
| 29 | |
| 30 | # the paginator knows how many hits and pages it contains |
| 31 | >>> paginator.hits |
| 32 | 9 |
| 33 | |
| 34 | >>> paginator.pages |
| 35 | 2 |
| 36 | |
| 37 | # get the first page (zero-based) |
| 38 | >>> paginator.get_page(0) |
| 39 | [Article 1, Article 2, Article 3, Article 4, Article 5] |
| 40 | |
| 41 | # get the second page |
| 42 | >>> paginator.get_page(1) |
| 43 | [Article 6, Article 7, Article 8, Article 9] |
| 44 | |
| 45 | # does the first page have a next or previous page? |
| 46 | >>> paginator.has_next_page(0) |
| 47 | True |
| 48 | |
| 49 | >>> paginator.has_previous_page(0) |
| 50 | False |
| 51 | |
| 52 | # check the second page |
| 53 | >>> paginator.has_next_page(1) |
| 54 | False |
| 55 | |
| 56 | >>> paginator.has_previous_page(1) |
| 57 | True |
| 58 | |
| 59 | """ |