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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…