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

I am using geodjango and have a collection of points in my database. To get the job of points in a specific 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 went through?

EDIT

I must mention that I am passing the coordinates and want to create an object with them Point. Then pass this point as a source and filter against it. For example, I 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 piece of code gives me this error:

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

I wonder 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))
+5
source share
3 answers

, , GeoDjango , - , post. , . , D. . , :

ValueError: Tuple required for `distance_lte` lookup type.

, order_by('distance')[:1][0]

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

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

closest_spot = Spot.objects.filter(point__distance_lte=(origin, D(m=distance_m))).distance(origin).order_by('distance')[:1][0]
+4
queryset = Spot.objects.distance(origin).filter(distance__lte=distance_m)
point = queryset.order_by('distance')[:1][0]

https://docs.djangoproject.com/en/dev/ref/contrib/gis/geoquerysets/#distance

0

, geodjango, . , ( 140000 ).

Story: the distance_lte function must calculate the distance to the origin for each row of the table and cannot use the geo-index. It seems that the dwithin function can use such indexes and there is no need to actually calculate the distance to the beginning for each row before the restriction is met, so it will be 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 geographic data in degrees ("1" in the request).

0
source

All Articles