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

后端 未结 3 1797
无人及你
无人及你 2021-02-09 17:45

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         


        
3条回答
  •  鱼传尺愫
    2021-02-09 18:29

    Finally a solution gathered from clues from GeoDjango distance filter with distance value stored within model - query which lead me to this post. From this information I was able to gather that you MUST SPECIFY the measure parameter in your distance query. You will see in the below snippet, I import measure as D. Then use it in the query. If you don't specify it you will get this error:

    ValueError: Tuple required for `distance_lte` lookup type.
    

    To take just the point with the lowest distance I used 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]
    

提交回复
热议问题