gpt4 book ai didi

django - 使用JsonResponse分页

转载 作者:行者123 更新时间:2023-12-04 11:18:56 25 4
gpt4 key购买 nike

我想在我的JsonResponse中添加分页。

我目前正在使用django.http.JsonResponse从 Elasticsearch API生成json。我想添加一个分页功能。我的代码如下:

class ResultQueryView(View):
def get(self, request):
resource_meta = request.GET.getlist("resource_meta")
locations = request.GET.getlist("location")
page = request.GET.get("page")
logger.info("Got search query where resource_meta: {} and locations: {}".format(resource_meta, locations))
results = resource_query(resource_meta, locations)
resource_ids = [r["_id"] for r in results['hits']['hits']]
resources = get_enriched_resources(request.user, Resource.objects.filter(internal_id__in=resource_ids))
serialized = ResourceSerializer(resources, many=True)
return JsonResponse({"resources": serialized.data})

最佳答案

使用Django的Paginator

from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
class ViewPaginatorMixin(object):
min_limit = 1
max_limit = 10

def paginate(self, object_list, page=1, limit=10, **kwargs):
try:
page = int(page)
if page < 1:
page = 1
except (TypeError, ValueError):
page = 1

try:
limit = int(limit)
if limit < self.min_limit:
limit = self.min_limit
if limit > self.max_limit:
limit = self.max_limit
except (ValueError, TypeError):
limit = self.max_limit

paginator = Paginator(object_list, limit)
try:
objects = paginator.page(page)
except PageNotAnInteger:
objects = paginator.page(1)
except EmptyPage:
objects = paginator.page(paginator.num_pages)
data = {
'previous_page': objects.has_previous() and objects.previous_page_number() or None,
'next_page': objects.has_next() and objects.next_page_number() or None,
'data': list(objects)
}
return data

现在,使用 ViewPaginatorMixin支持 View的分页
class ResultQueryView(ViewPaginatorMixin, View):
def get(self, request):
// code
serialized = ResourceSerializer(resources, many=True)
return JsonResponse({"resources": self.paginate(serialized.data, page, limit)})

关于django - 使用JsonResponse分页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49035909/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com