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

后端 未结 3 1798
无人及你
无人及你 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]
    
    0 讨论(0)
  • 2021-02-09 18:29
    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 讨论(0)
  • 2021-02-09 18:36

    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).

    0 讨论(0)
提交回复
热议问题