How to return a record with the lowest distance from a point using geodjango?

Viewed 4564

I am using geodjango and have a collection of points in my database. To get a queryset of points within a certain area I use this:

queryset = Spot.objects.filter(point__distance_lte=(origin, distance_m))

My question is how can I return only one point(the point with the lowest distance)from the point I have passed it?

EDIT

I should mention that I am passing in coordinates and wanting to create a Point object with them. Then pass that point in as the origin and filter against that. For example I have tried:

from spots.models import *
from django.contrib.gis.geos import *

origin = Point(28.011030, -26.029430)
distance_m = 1000

queryset = Spot.objects.filter(point__distance_lte=(origin, distance_m))
for q in queryset:
    print q.distance

This snippet of code gives me this error:

Traceback (most recent call last):
  File "<console>", line 2, in <module>
AttributeError: 'Spot' object has no attribute 'distance'

Interestingly enough if I do the following:

origin = Spot.objects.get(name='Montecasino').point
distance_m = 1000

for city in Spot.objects.distance(origin):
    print(city.name, city.distance)

(u'Design Quarter Parking', Distance(m=677.347841801))
(u'Montecasino', Distance(m=0.0))
(u'Fourways', Distance(m=1080.67723755))
3 Answers

I was looking for an example on how to sort results against a location with geodjango, so my use case was very close to this one. Though the accepted solution worked, performances was very bad for a big data set (more than 140000 rows).

Short story: the distance_lte function must calculate distance to origin for each row of the table and can't make use of geo indexes. It appears that the dwithin function can make use of such indexes and don't need to actually calculate the distance to origin for each row before before the restriction is done, so it's way more efficient:

origin = Point(28.011030, -26.029430)
closest_spot = Spot.objects.filter(point__dwithin=(origin, 1)) \
    .distance(origin).order_by('distance')[:1][0]

The dwithin function works with geographical data in degree (the "1" in the query).

Related