问题
I'm trying to return a queryset 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)
What I need to return are the Label objects which have a certain tag/tags ordered by distance from a given point.
The Labels can be found by:
Label.objects.filter(hashtags__in=tags)
Distances are available on Store objects calculated with:
Store.objects.filter(label__hashtags__in=tags)
.distance(location).order_by('distance')
What I'd like to do is perform a query on the Label
table to return everything but I suspect this is not possible.
Trying the distance
method on the queryset results in:
TypeError: ST_Distance output only available on GeometryFields.
Failing that it would make sense to do the most efficient next best thing. The only solution I can come up with is to perform both queries and merge the results into a set.
回答1:
It is definitely possible to achieve your query:
- Use the annotate() to append a distance value on every
Label
object. - Use the Distance() function to calculate the distance between each store's
geopoint
and thelocation
point
The query 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')
来源:https://stackoverflow.com/questions/30082265/geodjango-distance-of-related-model