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?
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).
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})