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

后端 未结 3 1790
无人及你
无人及你 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: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).

提交回复
热议问题