0

If for instance, my Django table has hundreds of rows and initially, in a view, I fetch first 10 records in the following format to be displayed on a webpage.

def fetchtExperts(request):
    if request.method == "GET":
        experts = Experts.objects.exclude(client_assigned=None).values('id', 'name', 'age').order_by('qualification')[:10]

    return render(request, 'index.html', {'experts': experts})

If these 10 records are displayed on page 1, I want the next 10 records to be displayed when the user clicks on page 2. How do I fetch the next 10 records starting from the record succeeding the last fetched record? Do I send page 1's last record's ID to the view so that I could fetch the next 10 records accordingly or is there some better approach to achieve this?

1 Answer 1

1

Django provide Pagination tool for such kind of problems. Change your view:

from django.core.paginator import Paginator

def fetchtExperts(request):
    experts = Experts.objects.exclude(client_assigned=None).values('id', 'name', 'age').order_by('qualification')
    paginator = Paginator(experts, 10) # Show 10 contacts per page

    page = request.GET.get('page')
    experts = paginator.get_page(page)
    return render(request, 'list.html', {'experts': experts})

With this method you need to pass page number as GET argument: http://mypage.com/view?page=1

Sign up to request clarification or add additional context in comments.

6 Comments

I tried this but I'm not able to iterate through objects in the template. I'm able to view the objects using {{ experts.object_list }}. I am able to send the page number through GET as you mentioned but I am missing something. I checked the docs.djangoproject.com/en/2.0/topics/pagination/… and it is similar to your answer, the iteration through Querset in the template is also normal but I'm not able to emulate the results.
No error, i just cant iterate. It's not of the Queryset data-type. If I print experts just before render (I've used your code) I get <Page 2 of 2> But if I print experts.object_list I can see the list of all the objects like this [{'id': 28, 'name': 'q8', 'age': 20}, {'id': 29, 'name': 'asdasd', 'age': 26]
@hulkinBrain how do you iterate?
Like this {% for expert in experts %} {{ expert.name }} {% endfor %}
Nevermind I figured it out, I just had to pass paginator.page(page) as context instead of experts as it is. Thanks for the answer! Cheers
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.