GeoDjango distance from linked model

I am trying to return a set of queries with distances from a related model. (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:



Distances are available for Store objects calculated using:



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

1 answer

You can definitely fulfill your request:

The request should look like this:

from django.contrib.gis.db.models.functions import Distance

             .annotate(distance=Distance('store__geopoint', location))




All Articles