djangodjango-paginationdjango-3.2

Django 3.2.3 Pagination isn't working properly


I have a Class Based View who isn't working properly (duplicating objects and deleting some) Tested it in shell

from django.core.paginator import Paginator
from report.models import Grade, Exam

f = Exam.objects.all().filter(id=7)[0].full_mark
all = Grade.objects.all().filter(exam_id=7, value__gte=(f*0.95)).order_by('-value')
p = Paginator(all, 12)
for i in p.page(1).object_list:
...     print(i.id)

2826 2617 2591 2912 2796 2865 2408 2501 2466 2681 2616 2563

for i in p.page(2).object_list:
...     print(i.id)

2558 2466 2563 2920 2681 2824 2498 2854 2546 2606 2598 2614


Solution

  • Making an order_by call before passing the query_set all to the pagination is the root of the problem and well explained here. All you need is to call distinct() or specify another field in the order_by to use in case of same value.

    Below is the code that should work, you also don't need to use all() in your queries. The filter by default applies on all the model objects.

    from django.core.paginator import Paginator
    from report.models import Grade, Exam
    
    f = Exam.objects.filter(id=7).first().full_mark
    all = Grade.objects.filter(exam_id=7, value__gte=(f*0.95)).order_by('-value').distinct()
    p = Paginator(all, 12)
    for i in p.page(1).object_list:
    ...     print(i.id)
    

    By the way, your code will crash if an exam object with id=7 is not found. You should assign the full_mark value to your f variable conditionally.