Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
898 views
in Technique[技术] by (71.8m points)

python - GeoDjango filter by distance from a model field

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...