Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

237
Views
How to get the next n records in a django queryset?

Is there a way to get the next n records in django queryset?

For example, how would I get the next 5 records after getting the first five records? My use case is that I have a see more button on my page and I want to load the next 5 records whenever the see more button is clicked (via ajax)

I would like to do something like this

#function that handles ajax
def load_next_five(initial_five)
    next_five = initial_five.???
    return JsonResponse({'next_five': list(next_five)})

def main_view(request):
    initial_five = Car.objects.filter(year__gte=2000)
    ...

How would I go about the load_next_five function?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

use a slice. You'll have to pass in where you want to start.

def load_next_five(start)
    next_five = Car.objects.filter(year__gte=2000)[start:start+5]
    return JsonResponse({'next_five': list(next_five)})

def main_view(request):
    initial_five = Car.objects.filter(year__gte=2000)[:5]

Under the covers, Django will turn that into clauses that will limit the results on the database side (for example, LIMIT and OFFSET).

over 4 years ago · Santiago Trujillo Report

0

Follow the django paginator, easy to use.

def load_next_five(request):
    car_obj = Car.objects.all()
    paginator = Paginator(car_obj, 5) # change this number as you required
    page = request.GET.get('page')

    try:
        cars = paginator.page(page)
    except PageNotAnInteger:
        cars = paginator.page(1)
    except EmptyPage:
        cars = paginator.page(paginator.num_pages)

    return JsonResponse({'cars': cars})
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!