Search code examples
pythondjangodjango-viewsdjango-querysetdjango-filter

django-filter AssertionError: Cannot filter a query once a slice has been taken


I'm using Django-filter ,I want to slice the rows ,just want the first 75 row:

def hist_view_render(request):
    all_obj =  RunStats.objects.all().order_by('-create_dttm')[:75]
    hist_filter = RunStatsFilter(request.GET, queryset=all_obj)
    paginator= Paginator(hist_filter.qs, 15)
    page = request.GET.get('page')

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

    context =  {'response': response,'filter': hist_filter}

    return render(request, 'runstat_hist.html',context)

I have tried put the [:75] in different places ,but I always receive the error:

  Cannot filter a query once a slice has been taken

The only way that works is slice it in the template ,but I want to find a way to slice it in the views.py.

Any friend can help ?


Solution

  • The issue occurs when the paginator slices the queryset to get the object list for the page. You can pass a list to the paginator instead so that the slice does not raise the error

    all_obj =  RunStats.objects.all().order_by('-create_dttm')
    hist_filter = RunStatsFilter(request.GET, queryset=all_obj)
    paginator = Paginator(list(hist_filter.qs[:75]), 15)