[Answered ]-Django pagination while objects are being added

2👍

One approach you could take is to send the oldest ID that the client currently has (i.e., the ID of the last item in the list currently) in the AJAX request, and then make sure you only query older IDs.

So get_images_paginated is modified as follows:

def get_images_paginated(query, origins, page_num, last_id=None):
    args = None
    queryset = Image.objects.all().exclude(hidden=True).exclude(tags__isnull=True)
    if last_id is not None:
        queryset = queryset.filter(id__lt=last_id)
    ...

You would need to send the last ID in your AJAX request, and pass this from your view function to get_images_paginated:

def get_images_ajax(request):
    if not request.is_ajax():
        return render(request, 'home.html')

    query = request.POST.get('query')
    origins = request.POST.getlist('origin')
    page_num = request.POST.get('page')
    # Get last ID. Note you probably need to do some type casting here.
    last_id = request.POST.get('last_id', None)

    images, amount = get_images_paginated(query, origins, page_num, last_id)
    ...

As @doniyor says you should use Django’s built in pagination in conjunction with this logic.

Leave a comment