django-filter AssertionError:一旦取了切片就不能过滤查询



我使用Django-filter,我想切片行,只需要前75行:

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)

我试着把[:75]放在不同的地方,但我总是收到错误:

Cannot filter a query once a slice has been taken

唯一有效的方法是在模板中切片,但我想找到一种在views.py中切片的方法。

有朋友可以帮忙吗?

当分页器对查询集进行切片以获取该页的对象列表时,会发生此问题。您可以将列表传递给分页器,这样切片就不会引发错误

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)

相关内容

  • 没有找到相关文章

最新更新