From 4176814412fe12cd0aea598ef5807bb56964d8dd Mon Sep 17 00:00:00 2001 From: Sanj Date: Wed, 31 Aug 2011 17:44:02 +0530 Subject: [PATCH] implement pagination in back-end --- gazetteer/places/views.py | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/gazetteer/places/views.py b/gazetteer/places/views.py index 362c22f..b97de58 100644 --- a/gazetteer/places/views.py +++ b/gazetteer/places/views.py @@ -3,6 +3,7 @@ from django.shortcuts import render_to_response, get_object_or_404 from ox.django.shortcuts import render_to_json_response from django.template import RequestContext from models import Feature, FeatureType, AuthorityRecord +from django.core.paginator import Paginator, InvalidPage, EmptyPage def search(request): d = RequestContext(request, {}) @@ -12,6 +13,8 @@ def search_json(request): search_term = request.GET.get("q", "") threshold = request.GET.get("threshold", 0.5) bbox = request.GET.get("bbox", False) + page = request.GET.get("page", 1) + count = request.GET.get("count", 100) country = request.GET.get("adm0", "US") # right now, unused adm1 = request.GET.get("adm1", "") adm2 = request.GET.get("adm2", "") @@ -33,10 +36,22 @@ def search_json(request): if not bbox and not search_term: return render_to_json_response({'error': 'must supply either a valid `bbox` or a `search` parameter'}) - features_qset = Feature.search.find(bbox=bbox, text=search_term, threshold=threshold, adm1=adm1, adm2=adm2, srid=srid)[0:20] - features = [f.get_geojson(srid) for f in features_qset] + features_qset = Feature.search.find(bbox=bbox, text=search_term, threshold=threshold, adm1=adm1, adm2=adm2, srid=srid) + total_results = features_qset.count() + paginator = Paginator(features_qset, count) + num_pages = paginator.num_pages + + try: + results = paginator.page(page) + except (EmptyPage, InvalidPage): + results = paginator.page(paginator.num_pages) + features = [f.get_geojson(srid) for f in results.object_list] + d = { 'type': 'FeatureCollection', + 'results': total_results, + 'current_page': page, + 'pages': num_pages, 'features': features } return render_to_json_response(d)