GeoDjango distance from linked model
I am trying to return a set of queries with distances from a related model.
models.py (simplified)
class Store(models.Model):
geopoint = models.PointField(srid=4326)
objects = models.GeoManager()
class HashTag(models.Model):
tag = models.CharField(max_length=100)
class Label(models.Model):
hashtags = models.ManyToManyField(HashTag)
store = models.ForeignKey(Store)
I need to return Label objects that have specific tags / tags ordered by distance from a given point.
Find labels by:
Label.objects.filter(hashtags__in=tags)
Distances are available for Store objects calculated using:
Store.objects.filter(label__hashtags__in=tags)
.distance(location).order_by('distance')
What I would like to do is execute a query on the table Label
to return everything, but I suspect this is not possible.
Attempting a method distance
in a request calls:
TypeError: ST_Distance output only available on GeometryFields.
If not, it would be wise to do the most efficient next best thing. The only solution I can think of is to execute both queries and combine the results into a set.
source to share
You can definitely fulfill your request:
- Use
annotate()
to add a distance value for each objectLabel
. - Use a function
Distance()
to calculate the distance between each storegeopoint
and pointlocation
The request should look like this:
from django.contrib.gis.db.models.functions import Distance
Label.objects.filter(hashtags__in=tags)
.annotate(distance=Distance('store__geopoint', location))
.order_by('distance')
source to share