GeoDjango filter by distance from a model field

荒凉一梦 提交于 2019-12-07 06:04:15

问题


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 a model that is something like:

class Person(models.Model):
    location = models.PointField(srid=4326)
    willing_to_travel = models.IntegerField()

If I want all instances of Person who are within a set distance (e.g. 10 miles) of a point p, I can do it like this:

Person.objects.filter(location__distance_lte=(p, D(mi=10)))

But I would like to get all instances of Person who are within their willing_to_travel distance of a particular location.


回答1:


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.



来源:https://stackoverflow.com/questions/32609729/geodjango-filter-by-distance-from-a-model-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!