🎸 Django Intermediate

What is Django pagination?

Why Interviewers Ask This

Candidates at the intermediate level are expected to not only know this concept but explain the trade-offs involved. Interviewers use this question to see if you can reason about design decisions, not just recall facts.

Answer

Django's built-in Paginator class divides a queryset or list into pages: In views: from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger def article_list(request): queryset = Article.objects.filter(is_published=True) paginator = Paginator(queryset, per_page=10) page_number = request.GET.get("page", 1) try: page = paginator.page(page_number) except (PageNotAnInteger, EmptyPage): page = paginator.page(1) return render(request, "articles/list.html", {"page": page, "articles": page.object_list}). Template: {% for article in articles %}...{% endfor %} {% if page.has_previous %}<a href="?page={{ page.previous_page_number }}">Previous</a>{% endif %} Page {{ page.number }} of {{ page.paginator.num_pages }} {% if page.has_next %}<a href="?page={{ page.next_page_number }}">Next</a>{% endif %}. ListView pagination: just set paginate_by = 10 — automatic. Template variable: page_obj and paginator. DRF pagination: REST_FRAMEWORK = {"DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination", "PAGE_SIZE": 20}. Custom: class StandardPagination(PageNumberPagination): page_size = 20; page_size_query_param = "per_page"; max_page_size = 100. Response: {"count": 500, "next": "http://api.example.com/articles/?page=3", "previous": "...", "results": [...]}. Cursor pagination (DRF): for infinite scroll — more efficient than OFFSET for large datasets.

Common Mistake

Rushing to answer is a common mistake. Take two seconds to structure your response: definition → example → trade-off. This structure makes complex Django answers easy to follow.