Skip to content

Commit

Permalink
Use aggregate function rather than QS method.
Browse files Browse the repository at this point in the history
  • Loading branch information
dracos committed Feb 12, 2015
1 parent fc2f6c3 commit 069ed23
Showing 1 changed file with 8 additions and 8 deletions.
16 changes: 8 additions & 8 deletions mapit/views/postcodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from django.shortcuts import redirect, render
from django.contrib.gis.geos import Point
from django.contrib.gis.measure import D
from django.contrib.gis.db.models import Collect

from mapit.models import Postcode, Area, Generation
from mapit.utils import is_valid_postcode, is_valid_partial_postcode
Expand Down Expand Up @@ -99,16 +100,15 @@ def partial_postcode(request, postcode, format='json'):
postcode = re.sub('\d[A-Z]{2}$', '', postcode)
if not is_valid_partial_postcode(postcode):
raise ViewException(format, "Partial postcode '%s' is not valid." % postcode, 400)
try:
postcode = Postcode(
postcode=postcode,
location=Postcode.objects.filter(postcode__startswith=postcode).extra(
where=['length(postcode) = %d' % (len(postcode) + 3)]
).collect().centroid
)
except:

location = Postcode.objects.filter(postcode__startswith=postcode).extra(
where=['length(postcode) = %d' % (len(postcode) + 3)]
).aggregate(Collect('location'))['location__collect']
if not location:
raise ViewException(format, 'Postcode not found', 404)

postcode = Postcode(postcode=postcode, location=location.centroid)

if format == 'html':
return render(request, 'mapit/postcode.html', {
'postcode': postcode.as_dict(),
Expand Down

0 comments on commit 069ed23

Please sign in to comment.