GeoDjango filter by distance from a model field

前端 未结 1 1862
粉色の甜心
粉色の甜心 2020-12-11 05:19

My question is pretty much the same as this. But its quite old and it feels like it must be a fairly common scenario that there might be a better solution to.

I have

1条回答
  •  醉梦人生
    2020-12-11 05:51

    It is possible thanks to Geographic Database Functions introduced in Django 1.9

    allow users to access geographic database functions to be used in annotations, aggregations, or filters in Django.

    The one that interests us the most is Distance, it can be applied in your case as follows:

    from django.contrib.gis.db.models.functions import Distance
    from django.db.models import F
    Person.objects.annotate(distance=Distance('location', p)
           ).filter(distance__lte=F('willing_to_travel'))
    

    Notice that there is subtle difference here, instead of directly using distance_lte here, we have created an annotation that yields us a distance column. Then we are using the standard __lt comparision from the model queryset on it. This translates (roughly) in to

       ... WHERE ST_Distance(app_person.location, ST_GeogFromWKB(...)) < 
           app_person.willing_to_travel
    

    Which is similar to the one produced by distance_lte It's not as efficient as one that uses ST_Dwithin but it does the job

    you would need to convert location to geography because this query operates on 'units of the field' which means degrees. If you use geography fields the distance will be in meters.

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