Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 849
lac Avatar asked Sep 16 '15 13:09

lac


1 Answers

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.

like image 76
e4c5 Avatar answered Nov 03 '22 05:11

e4c5